/**
    * 表单展示页（填写）
 *
*/
mini.parse();
// 用户信息（从缓存中取）
var item2 = localStorage.getItem("item");
var userInfoObj = JSON.parse(item2);
var arr_child = [];// 存放保存子表数据
var arr_main = { // 存放格式化的保存数据

    "cTableName": "",
    "obj": {}
};
var inner_obj = {};
var arr_table = [];// 生成表格组件数组
var arr_tab_table = [];// 生成tab表格组件数组
var arr_tab = [];
var datepick_main = [];
var datepick_child = [];
var pid_data = [];
var save_data = [];
var tableAll = [];// 所有表格的数组，用于删除后清空表格

var arr_cMath_main = [];// 所有主表公式
var arr_cMath_child = [];// 所有子表公式

var currentCell; // 当前点击的单元格field,用于公式
var formRefData = [];// 设置参照
var formId;
var action;
var innerMode;// 页面内edit模式
var formCode;
var formSh;
var menuId;
var menusFormTypes;
var treeSelected;// 树形选中的数据
var textField;// 树形字段名
var textFieldValue;// 树形字段名对应值
var refField;// 树形参照对应的组件name
var nodes = [];// 树形带来的数据
var refFields = {};// 所有的参照的字段
var complex_add_fields = [];// 树形参照保存时新增的字段
var complex_add_values = {};// 树形参照保存时新增的字段值
var reSelectFlag = false;// 树形参照带过来的字段是否重选
var component_data;
var mTableName;//主表名
var sTableName;//子表名
var edit_data;
var save_backData;//保存后返回的数据
var edit_form = [];// 编辑的表单数据
var edit_table = [];// 编辑的表格数据
var single_person_data = [];// 制单人数据
var formItem = parent.getFormItem();// 菜单跳转后获取数据
var singleObj = {}; // 制单人
var url = bootPATH + "../frame/frame1/pages/";      //路径前缀
var cFormName; // 表单名称
var formState;  //单据状态(提交/审批等状态)
//var dayState = '';      //时间计算信号量
var clickStatus;        //列表跳转页面时是双击还是点击编辑按钮
var ids;
var fujian=[];



// 初始化执行
formInit();
// 初始化表单
function formInit() {
    //单据列表页跳转时数据
    formSh = localStorage.getItem("formShow");
    //缓存中获取当前登录用户信息
    userInfo = localStorage.getItem("item");
    // var param = setLinkage(e, arr_cMath_main[i].math, str, 'base');
    //根据跳转类型判断按钮显示
    if (formSh == undefined) {// 菜单跳转，add
        formId = formItem.item.formListId;
        menuId = formItem.item.id.match(/menuId(\S*)/)[1];
        menusFormTypes = formItem.item.menusFormTypes;
        action = 'add';

        mini.get("add").enable();
        mini.get("edit").disable();
        mini.get("save").disable();
        mini.get("remove").disable();
        mini.get("cancel").disable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").disable();
        mini.get("submission").disable();

        mask();
    } else {// 按钮跳转，add/edit
        formSh = $.parseJSON(formSh);
        menuId = formSh.menuId;
        console.log(formSh, 'formShow');
        action = formSh.action;                 //按钮状态（编辑/新增）
        clickStatus = formSh.clickStatus;       //双击跳转页面还是点击编辑跳转页面
        formId = formSh.formListId;
        menusFormTypes = formSh.menusFormTypes;
        //获取当前单据状态
        formState = formSh.formState;
    }
    if (menusFormTypes == 'complex') {
            treeSelected = formSh.treeSelected;// 档案需要赋值的数据
            textField = formSh.textField;
            textFieldValue = treeSelected[textField];
            var nodes = formSh.nodes;
            complex_add_values[treeSelected.tabName + '_id'] = treeSelected.id;
            for (var p = 0; p < nodes.length; p++) {
                complex_add_values[nodes[p].tabName + '_id'] = nodes[p].id;
            }

            nodes = formSh.nodes;
            console.log(complex_add_values, 'complex_add_values');
        } else if (menusFormTypes == 'treeFile') {
            console.log('如果类型是单个属性档案');
        } else if (menusFormTypes == 'file') {
            console.log('类型是列表档案');
        }
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").enable();
        mini.get("copy").disable();

        unmask();
    }

if (action == 'edit') {// 编辑
    //判断点击状态是双击还是单击
    if(clickStatus == 'rowdblclick'){
        //隐藏按钮栏
        $('#formToolbar').hide();
        // mini.get("add").disable();
        // mini.get("edit").disable();
        // mini.get("save").disable();
        // mini.get("cancel").disable();
        // mini.get("remove").disable();
        // mini.get("approve").disable();
        // mini.get("abandon").disable();
        // mini.get("refer").disable();
        // mini.get("submission").disable();
        // mini.get("budgetsearch").disable();
    }else{
        switch (formState) {
            case '0':
                mini.get("add").enable();
                mini.get("edit").enable();
                mini.get("save").disable();
                mini.get("cancel").disable();
                break;
            case '':
                mini.get("add").enable();
                mini.get("edit").enable();
                mini.get("save").disable();
                mini.get("cancel").disable();
                break;
            case '1':
                mini.get("add").disable();
                mini.get("edit").disable();
                mini.get("save").disable();
                mini.get("remove").disable();
                mini.get("cancel").disable();
                mini.get("approve").disable();
                mini.get("abandon").disable();
                mini.get("refer").disable();
                mini.get("submission").disable();
                mini.get("budgetsearch").disable();
                break;
            case null:
                mini.get("add").enable();
                mini.get("edit").enable();
                mini.get("save").disable();
                mini.get("cancel").disable();
                break;

        }
    }
    edit_data = formSh.edit_data;
    // formCode = edit_data[0].formCode;
    console.log(edit_data, 'edit_data');
} else {
    edit_data = [];
}

    // 画按钮
    initBtn();
    // mask();

    // 画组件
    var url = ajaxUrl + "/formltems/findByFormListId.do";
    $.ajax({
        type: 'post',
        url: url,
        data: {
            formId: formId
        },
        dataType: 'json',
        success: function (data) {
            console.log(data);
            //	获取主子表关系
            $.ajax({
                url: ajaxUrl + "/tableClass/tableRelations.do",
                // url: "http://192.168.31.65:8080",
                type: "post",
                // dataType: "json",
                traditional: true,
                data: {
                    formId: formId
                },
                success: function (relation) {
                    console.log(relation, '主子表关系');
                    mTableName = relation.mTableName;
                    sTableName = relation.sTableName;

                    component_data = data['data'];
                    console.log(component_data, '组件');
                    for (var i = 0; i < component_data.length; i++) {
                        if (component_data[i].type == 'tab') {
                            arr_tab.push(component_data[i]);
                        }
                        if (component_data[i].type.indexOf('datepicker') > -1) {
                            datepick_main.push(component_data[i]);
                        }
                        if (component_data[i].cMath == "") {
                            component_data[i].cMath = JSON.stringify(component_data[i].cMath);
                        }
                        if (component_data[i].cTableField.indexOf('single_person') > -1 && component_data[i].type != "table") {// 制单人
                            single_person_data.push(component_data[i]);
                        }
                        if(component_data[i].cRefObj.disable=="true"){
                            component_data[i].id.disable();
                        }
                        if (component_data[i].type.indexOf('buttonedit') > -1) {

                            if (component_data[i].ref != "{}") {
                                var item = $.parseJSON(component_data[i].ref).ref.cTableField;// group_name
                                var tabName = $.parseJSON(component_data[i].ref).ref.cTableName;//

                                if (nodes != null) {
                                    for (var k = 0; k < nodes.length; k++) {
                                        for (var nod in nodes[k]) {
                                            if (item == nod && tabName == nodes[k].tabName) {// 保存参照的字段
                                                refFields[component_data[i].cTableField] = nodes[k][item];
                                            }
                                        }
                                    }
                                }

                            }
                            if (component_data[i].cTableField == "parent_level") {// 父级id字段
                                pid_data.push(component_data[i]);
                            }
                        }
                    }
                    create_tab(arr_tab);
                    showForm(component_data);// 渲染
                    // 编辑赋值
                    if (action == 'edit') {
                        console.log(edit_data);
                        var formField = $("#formField").children();
                        for (var i = 0; i < formField.length; i++) {
                            console.log(formField[i], '表单下所有组件');
                            if (formField[i].className == 'form_items') {// 主表组件

                                var form = new mini.Form("#" + formField[i].id);
                               // 得到主表数据
                                //var mainFormData = edit_data[formSh.cTableName][0];
                                console.log(formSh);
                                formSh9=mini.clone(formSh);
                                fujian=[];
                                fujian.push(formSh9.cTableName);
                                cTableName=formSh9.cTableName;
                                formSh9.edit_data[cTableName][cTableName+"_id"]=intercept(formSh9.edit_data[cTableName][cTableName+"_id"],0);
                                fujian.push(formSh9.edit_data[cTableName] [cTableName+"_id"]);
                                console.log(fujian);
                                var ccc = formSh.cTableName;
                                var mainFormData = edit_data[formSh.cTableName];
                                console.log(typeof mainFormData);
                                var newMainFormData  = {};
                                //处理主表数据
								for(var key in mainFormData){
								    console.log(typeof mainFormData[key])
									if(mainFormData[key].indexOf('null') == -1){
                                        newMainFormData[key] = mainFormData[key].split('_')[1];
									}else{
                                        newMainFormData[key] = '';
									}
								}
                                //处理单据状态显示
                                switch (newMainFormData[formSh.cTableName + '_state']) {
                                    case '0':
                                        newMainFormData[formSh.cTableName + '_state'] = '未提交';
                                        break;
                                    case '1':
                                        newMainFormData[formSh.cTableName + '_state'] = '已提交';
                                        break;
                                    case '2':
                                        newMainFormData[formSh.cTableName + '_state'] = '审批中';
                                        break;
                                    case '3':
                                        newMainFormData[formSh.cTableName + '_state'] = '终审';
                                        break;
                                    case '4':
                                        newMainFormData[formSh.cTableName + '_state'] = '驳回';
                                        break;
                                    case '5':
                                        newMainFormData[formSh.cTableName + '_state'] = '中止';
                                        break;
                                    case '6':
                                        newMainFormData[formSh.cTableName + '_state'] = '撤回';
                                        break;
                                    default:
                                        newMainFormData[formSh.cTableName + '_state'] = '未提交';
                                }
                                //赋值
                                //form.setData(edit_data[formSh.cTableName][0], false);
                                form.setData(newMainFormData, false);
                                var index = formField[i].id.indexOf('buttonedit')
                                var index2 = formField[i].id.indexOf('datepicker')
//								if (index2 > -1) {
//
//								}
                                if (index > -1 || index2 > -1) {
//                                     for (var item in edit_data[formSh.cTableName][0]) {
//                                         var setBE = edit_data[formSh.cTableName][0];
//                                         if (item == formField[i].children[1].children[1].name) {
//                                             mini.get("right" + formField[i].id)
//                                                 .setText(setBE[item]);
// //											mini.get("right" + formField[i].id)
// //											.setValue(setBE[item]);
//                                         }
//                                     }
                                }
                                for (var item in mainFormData) {
                                    var setBE = mainFormData;
                                    if (item == formField[i].children[1].children[1].name) {
                                        if(setBE[item].indexOf('null') != -1){
                                            setBE[item] = '';
                                        }
                                        mini.get("right" + formField[i].id)
                                            .setText(setBE[item].split('_')[1]);
                                        mini.get("right" + formField[i].id)
                                            .setValue(setBE[item].split('_')[0]);
//											mini.get("right" + formField[i].id)
//											.setValue(setBE[item]);
                                    }
                                }
                                //edit_form = edit_data[formSh.cTableName][0];
                                edit_form = edit_data[formSh.cTableName];
                                console.log(edit_data[formSh.cTableName],'编辑取值s');
                                console.log(edit_form,'编辑保存数据')

                            } else {// 表格
                                if (formField[i].className.indexOf('mini-menu') == -1) {
                                    var indexofBloean = formField[i].className.indexOf('mini-tabs');
                                    if(indexofBloean == 0){
                                        console.log('tab组件赋值');
                                        //获取子表组件(根据页签id获取当前页签)
                                        var nowTab = mini.get(formField[i].id);
                                        //获取页签组
                                        var childsTab = nowTab.getTabs();
                                        //页签内容区域存放
                                        var childTabContents = [];
                                        for(var j = 0; j < childsTab.length; j++){
                                            childTabContents.push(nowTab.getTabBodyEl(childsTab[j]));
                                        }
                                        var tabChildGridIds = [];
                                        var tabChildGridKeys = [];
                                        childTabContents.forEach(function (item,index){
                                            tabChildGridIds.push(item.childNodes[2].id);
                                            tabChildGridKeys.push(item.childNodes[2].id.split('_')[1]);
                                        });
                                        //得到数据表格
                                        tabChildGridIds.forEach(function (Iditem,index){
                                            tabChildGridKeys.forEach(function (keyItem,index){
                                                if(Iditem.indexOf(keyItem) != -1){
                                                    //得到表格，赋值
                                                    var tabGrid = mini.get(Iditem.match(/dg(\S*)/)[1]);
                                                    tabGrid.setData(edit_data[keyItem]);
                                                }
                                            });
                                        })
                                    }else{
                                        var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
                                        grid.setData("");
                                        var temp = formField[i].childNodes[2].className.split(' ');
                                        var mtableName;
                                        for (var m = 0; m < temp.length; m++) {
                                            if (temp[m].indexOf('mtable-') > -1) {
                                                mtableName = temp[m]
                                                    .substring(temp[m]
                                                        .indexOf("-") + 1);
                                            }
                                        }

                                        // var e =
                                        // edit_data[formField[i].id.substring(8)];
                                        // for(var k = 0; k <e.length; k++) {
                                        // e[k].cTableName =
                                        // formField[i].id.substring(8);//加入子表名
                                        // }
                                        if (edit_data[mtableName] == []) {
                                            grid.setData([{}, {}]);
                                        } else {
                                            grid.setData(edit_data[mtableName],
                                                false);
                                        }
                                        edit_table.push({
                                            cTableName: mtableName,
                                            obj: edit_data[mtableName]
                                        });
                                    }

                                }
                            }
                        }
                        unmask();
                    }
                    // 新增档案赋值
                    if (action == 'add' && menusFormTypes == 'complex') {
                        console.log(textField, 'textField');// 参照的字段
                        console.log(textFieldValue, 'textFieldValue');
                        console.log(nodes, '赋值nodes');// nodes里找参照的值（所属集团、所属公司）
                        console.log(refFields, 'refFields');

                        // var form = new mini.Form("#formField");
                        // form.setData(refFields);

                        var formField = $("#formField").children();
                        for (var i = 0; i < formField.length; i++) {
                            // console.log(formField[i].children[1].children[1].name,'好多children++++++++++++++++++++++++');

                            if (formField[i].className == 'form_items') {// 主表组件
                                var fieldName = formField[i].children[1].children[1].name;
                                console.log(fieldName, 'fieldName');// 表单需要赋值的组件name
                                for (var m in refFields) {
                                    if (fieldName == m) {
                                        mini.get("right" + formField[i].id)
                                            .setText(refFields[m]);
                                        mini.get("right" + formField[i].id)
                                            .setValue(refFields[m]);
                                    }
                                }

                            } else {// 表格
                                if (formField[i].className.indexOf('mini-menu') == -1) {
                                }
                            }
                        }
                        unmask();
                    } else if (action == 'add' && menusFormTypes == 'treeFile') {
                        console.log('新增单个树形档案');
                    }
                    // 新增赋值
                    if (action == 'add') {// pid
                        var form = new mini.Form("formField"); // 得到页面上的表单
                        console.log('add', form);
                        var singleObj = {
                            single_person_id: userInfoObj.userId,
                            single_person: userInfoObj.uName
                        }
//						form.setData(singleObj);
                        // 判断页面上是否有制单人
                        // if(){
                        // mini.get('').setText('制单人');
                        // mini.get('').setValue('制单人');
                        // }
                        // mini.get('right' + mTableName + '_single_person').setValue(userInfoObj.userName);
                        // mini.get('right' + mTableName + '_single_person_id').setValue(userInfoObj.userId);
                        var codingData = localStorage.getItem('coding');
                        console.log(codingData);
                        codingData = JSON.parse(codingData);
                        console.log(codingData);
                        form.setData(codingData);

                        for (var p = 0; p < pid_data.length; p++) {
                            mini.get('right' + pid_data[p].c_id).setText('');
                            mini.get('right' + pid_data[p].c_id).setValue('-1');
                        }

                        for (var q = 0; q < single_person_data.length; q++) {
                            if (single_person_data[q].cTableField.indexOf('single_person_id') > -1) {//制单人id
                                mini.get('right' + single_person_data[q].c_id).setText(userInfoObj.userId);
                                mini.get('right' + single_person_data[q].c_id).setValue(userInfoObj.userId);
                            } else {//制单人
                                mini.get('right' + single_person_data[q].c_id).setText(userInfoObj.uName);
                                mini.get('right' + single_person_data[q].c_id).setValue(userInfoObj.uName);
                            }
                        }
                    }
                    // localStorage.clear();
                    // localStorage.removeItem("formShow");

                },
                error: function (data) {
                }
            });
        },
        error: function (message) {
            // console.log(message);
        }
    })
// 初始化按钮
function initBtn() {
    $.ajax({
        type: 'post',
        url: ajaxUrl + "/buttons/findByState.do",
        // url : "http://192.168.31.65:8080/bpm/buttons/findByState.do",
        dataType: 'json',
        success: function (data) {
            console.log(data);
            for (var i = 0; i < data.data.length; i++) {
                switch (data.data[i].buttonText) {
                    case '增加':
                        $("#add").css({
                            display: "inline-block"
                        });
                        break;
                    case '修改':
                        $("#edit").css({
                            display: "inline-block"
                        });
                        break;
                    case '删除':
                        $("#remove").css({
                            display: "inline-block"
                        });
                        break;
                    case '取消':
                        $("#cancel").css({
                            display: "inline-block"
                        });
                        break;
                    case '保存':
                        $("#save").css({
                            display: "inline-block"
                        });
                        break;
                    case '参照':
                        $("#refer").css({
                            display: "inline-block"
                        });
                        // 参照下拉数据申请
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl + "/rule/findRefByModelId.do?fromListId=" + formId,
                            dataType: 'json',
                            contentType: "application/json",
                            success: function (data) {
                                console.log(data);
                                var popupMenu = '';
                                if (data.data.length > 0) {
                                    for (var i = 0; i < data.data.length; i++) {
                                        popupMenu += "<li iconCls='icon-open' onclick='openRef("
                                            + data.data[i].ruleId
                                            + ")'>"
                                            + data.data[i].cTableNameCH
                                            + "</li>\n";
                                    }
                                } else {
                                    popupMenu += "<li iconCls='icon-open'>暂无数据</li>\n";
                                }
                                $("#popupMenu").append(popupMenu);
                                mini.parse();
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                mini.alert('请求失败');
                            }
                        });
                        break;
                    case '打印':
                        $("#printEl").css({
                            display: "inline-block"
                        });
                        // 打印模板下拉数据申请
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl + "/PrintList/findAll.do?fromListId=" + formId,
                            //dataType: 'json',
                            contentType: "application/json",
                            success: function (data) {
                                console.log(data);
                                data = JSON.parse(data);
                                var printMenu = '';
                                if (data.data.length > 0) {
                                    for (var i = 0; i < data.data.length; i++) {
                                        printMenu += "<li iconCls='icon-open' onclick='openPrintModel("
                                            + data.data[i].printId
                                            + ")'>"
                                            + data.data[i].printingName
                                            + "</li>\n";
                                    }
                                } else {
                                    printMenu += "<li iconCls='icon-open'>暂无数据</li>\n";
                                }
                                $("#printMenu").append(printMenu);
                                mini.parse();
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                mini.alert('请求失败');
                            }
                        });
                        break;
                }

            }
        },
        error: function (message) {

        }
    })

}

// 实例化组件
function showForm(data) {
    console.log(data);
    cFormName = data[0].cFormName;
    $("#formName").append("<h1>" + cFormName + "</h1>");// 表标题

    for (var i = 0; i < data.length; i++) {

        var type = data[i].type;
        if (type.indexOf('tab_') > -1) {
            var id = data[i].tabs_id;
            var tabs = mini.get(id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,// 整个页签
                tab_id: data[i].tab_id // 插入的当前页签
            }
            create(type, data[i], "div[id='" + tabEl.id + "']");
        } else {
            create(type, data[i], '#formField');
        }
    }
    create_table(arr_table);
    create_table(arr_tab_table, 'tab');
}

function create(type, data, area) {

    if (type == 'table') {// 表格
        arr_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    } else if (type == 'tab') {// 页签
        // create_tab(data);
        // arr_tab.push(data);
    } else if (type == 'tab_table') {// tab表格
        arr_tab_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    } else {
        create_base(data, area);
    }
}

function create_txt(data, area) {
    console.log(data, 'data');
    if (data.cFontSize == '' || data.cFontSize == undefined) {
        data.cFontSize = 14;
    }
    var form_items = '<div id="' + data.c_id + '" class="form_items" '
        + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX
        + 'px;font-size:' + data.cFontSize + 'px">' + data.cFormTitle
        + '</div>';

    $(area).append(form_items);
    $('#' + data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight,
        "font-size": 14
        // "margin-bottom": 4
    });
    mini.parse();

}

function create_base(data, area) {
    console.log(data, 'data');
    var miniclass;
    if (area == '#formField') {
        miniclass = data.type;
    } else {
        miniclass = data.type.match(/tab_(\S*)/)[1];
    }
    if (miniclass.indexOf('checkbox') > -1) {
        miniclass = 'checkboxlist';
    }
    var form_items = '<div id="' + data.c_id + '" class="form_items" '
        + 'name="' + data.cTableField + '"'
        + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
        + '<label id="left' + data.c_id + '">' + data.cLadText
        + ':</label>\n' + '<input id="right' + data.c_id + '" name="'
        + data.cTableField + '"' + '   class="mini-' + miniclass
        + ' visibility" ';
    if (data.type.indexOf('datepicker') > -1) {
        form_items = '<div id="' + data.c_id + '" class="form_items" '
            + 'name="' + data.cTableField + '"'
            + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
            + '<label id="left' + data.c_id + '">' + data.cLadText
            + ':</label>\n' + '<input id="right' + data.c_id + '" name="'
            + data.cTableField + '"' + '   class="mini-' + miniclass
            + ' visibility" valueType="string"';
    } else if (data.type.indexOf('fileupload') > -1) {
        form_items = '<div id="' + data.c_id + '" class="form_items" '
            + 'name="' + data.cTableField + '"'
            + 'style="top:' + (data.iConY) + 'px;left:' + data.iConX + 'px">'
            + '<label id="left' + data.c_id + '">' + data.cLadText + ':</label>'
            + '<input id="right' + data.c_id + '" name="'
            + data.cTableField + '"' + '   class="mini-' + miniclass
            + ' visibility" valueType="string"' +
            '    flashUrl="swfupload/swfupload.swf"\n' +
            '    uploadUrl="/enclosure/uploadFile.do"\n' +
            '    onuploadsuccess="onUploadSuccess" \n' +
            '    onuploaderror="onUploadError" onfileselect="onFileSelect"\n'
        ;
    }

    // 必填
    if (data.cNull == 'true') {
        form_items += ' required="true"';
    } else {
        form_items += ' required="false"';
    }
    //因为是字符串所以这里我在转换一下子
    var sss=data.cRefObj;
    var ssa=JSON.parse(sss);
    console.log(ssa);
    console.log(form_items);
    //当新加的判断字段为false时，给他动态拼接onvalidation属性onGtzero(大于0)方法名
    if(ssa.cCannotbezero=="true"){

    }else if(ssa.cCannotbezero=="false"){

        form_items += 'onvalidation="onGtzero"';

    }
    //当disable的字段为true时给控件加禁止编辑属性
    if(ssa.disable=="true"){

    }else if(ssa.disable=="false"){
        form_items += 'enabled="false"';
    }

    // 验证
    if (data.cRequire == 'none' || data.cRequire == '' || data.cRequire == undefined) {

    } else {
        form_items += ' vtype="' + data.cRequire + '"';
    }
    if (data.type.indexOf('spinner') > -1) {
        form_items += ' decimalPlaces="'
            + data.cSpinner
            + '" allowNull="'
            + !data.cNull
            + '" value="null" allowLimitValue="false" ';
    }
    form_items += ' /></div>';
    $(area).append(form_items);
    mini.parse();
    arr_cMath_main.push({
        math: $.parseJSON(data.cMath).newStrEn
    });
    arr_cMath_main[arr_cMath_main.length - 1]['id'] = data.c_id;

    // console.log(data.type,$('#'+ data.c_id).css('marginTop'));
    $('#' + data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight - 15,
        // "margin-bottom": 4
    });
    $('.form_items>span>span').css({
        height: '98%'
    });

    $('#left' + data.c_id).css({
        width: data.iWidth - data.iLabWidth,
        height: data.iLabHeight - 15,
        "text-align": "center",
        "font-size": data.cFontSize + 'px',
        "vertical-align": "middle",
        "display": "inline"
    });
    $('#right' + data.c_id).css({
        width: data.iLabWidth,
        height: data.iLabHeight - 15
    });
    if (data.cFontSize != '' || data.cFontSize != undefined) {
        $('#' + data.c_id + '>span>span>input').css('cssText',
            'font-size:' + data.cFontSize + 'px !important')
    }
    mini.parse();

    // 主表公式
    var cMath = $.parseJSON(data.cMath).newStrEn;

    // 主表 值改变时，更新其他公式结果
    mini.get('#right' + data.c_id).on("valuechanged", function (e) {
        console.log(arr_cMath_main, '所有主表公式');
        // console.log(arr_cMath_child,'所有子表公式');
        console.log(data.c_id);
        // 遍历所有主表公式
        for (var i = 0; i < arr_cMath_main.length; i++) {
            var str = arr_cMath_main[i].math;
            if (str != '' && str != undefined) {
                var param = setLinkage(e, arr_cMath_main[i].math, str, 'base');
                str = param.str;
                var mathType = param.mathType;
                var linkId = param.linkId;// 关联类型设置的id
                if (mathType == 'mathType_link') {// 关联
                    console.log(str, str);
                    // var str2=mini.clone(str);
                    // str2=JSON.stringify(str2);
                    // console.log(str2);
                    // str=JSON.stringify(str);
                    if (str.fileldValue != undefined) {
                        alert("写错了");
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl
                                + '/formltems/casacade.do ',
                            dataType: 'json',
                            contentType: "application/json",
                            data:JSON.stringify(str),
                            success: function (data) {
                                // if(menusFormTypes ==
                                // 'complex') {
                                // for(var item in
                                // data.data[0]) {
                                // mini.get('right'+linkId).setValue(data.data[0][item]);
                                // }
                                // }else {
                                // mini.get('right'+linkId).setValue(data);
                                // }
                                if (data.data.length > 0) {
                                    for (var item in data.data[0]) {
                                        mini.get('right' + linkId).setValue(data.data[0][item]);
                                    }
                                }

                            },
                            error: function (jqXHR,
                                             textStatus,
                                             errorThrown) {
                                    alert("NNN");
                            }
                        })
                    } else {
                        // mini.get('right'+linkId).setValue('');
                    }

                } else if (mathType == 'mathType_sumCols') {

                } else if (mathType == 'mathType_cascade') { //级联
                    console.log("进入级联计算");
                    console.log(str, "str级联计算");
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl + '/formltems/casacade.do ',
                            dataType: 'json',
                            contentType: "application/json",
                            data: JSON.stringify(str),
                            success: function (data) {
                                console.log(data);
                                if (data.state == 'success') {
                                    var casa = data.data;
                                    console.log("casa:", casa[0]);
                                    // var casaJson = casa[0];
                                    var up = {};
                                    up[e.field] = data.vale;
                                    // var value = casaJson[returnFileld];
                                    console.log("value", data.vale);
                                    var thisstr = data.data[0].returnFileld;
                                    if (thisstr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                                        mini.get('right' + linkId).setText(data.vale);
                                        mini.get('right' + linkId).setValue(data.vale);
                                    }
                                }
                            },
                            error: function () {

                            }
                        }
                    )
                } else if (mathType == "mathType_code") {
                    console.log("进入编号规则设置");
                    var now = new Date();
                    console.log("======str:" + JSON.stringify(str));
                    var file = str.fileld;
                    var nowYmd
                    if (file=="newDate()"){
                        var year = now.getFullYear();
                        var month = now.getMonth();
                        if (month < 10) month = "0" + ( month + 1);
                        var date = now.getDate();
                        if (date <10) date = "0" + date;
                        nowYmd = year +""+ month +""+ date +"";
                    }

                    console.log("进入编码规则设置",nowYmd);
                    console.log("linkId",linkId);
                    $.ajax({
                        url: ajaxUrl + "/sqlAction/findCode.do",
                        type : 'post',
                        data : JSON.stringify(str),
                        dataType : 'json',
                        contentType: "application/json",
                        success : function (data) {
                            console.log(data);
                            var returnObject = $.parseJSON(data.data);
                            console.log(returnObject,"returnObject");
                            var value = returnObject.valu;
                            console.log("value",value);
                            var newCode = nowYmd +""+value;
                            // if (thisstr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                            mini.get('right' + linkId).setText(newCode);
                            mini.get('right' + linkId).setValue(newCode);
                            // }
                        },
                        error : function () {

                        }
                    })

                } else if (mathType == "mathType_findTableSum"){
                    console.log("进入跨表求和：mathType_findTableSum")
                    console.log("子表进入跨表求和str:" + str);
                    $.ajax({
                        url : ajaxUrl + '/sqlAction/findTableSum.do',
                        type : 'post',
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(str),
                        success : function (data) {
                            console.log("跨表求和data",data)
                            if (data.state == "success"){
                                var vale ;
                                if(data.data == ""){
                                    vale = null;
                                }else{
                                    vale = data.data;
                                }
                                mini.get('right' + linkId).setText(vale);
                                mini.get('right' + linkId).setValue(vale);
                            }else{
                                mini.alert(data.message);
                            }
                        },
                        error : function (data) {

                        }
                    })

                } else{// 计算或拼接
                    var thisStr = str.split('=')[0];// 可以赋值的字段
                    if (thisStr.indexOf(e.sender.name) == -1) {// 不等于已填写的字段，则赋值
                        mini.get('#right' + arr_cMath_main[i].id).setValue(evil(str));
                    }
                }
            }
        }

    });
    arr_main.cTableName = data.cTableName;
    arr_main.obj[data.cTableField] = "";

    // 主表 个性化
    if (data.type.indexOf('datepicker') > -1) {// 时间选择器
        if (data.cFormat != "" && data.cFormat != undefined) {
            mini.get('right' + data.c_id).setFormat(data.cFormat);
        }
    } else if (data.type.indexOf('spinner') > -1) {// 数值

    } else if (data.type.indexOf('combobox') > -1) {// 下拉框
        // console.log(data.cCombo);
        var combo_arr = data.cCombo.split(/[(\r\n)\r\n]+/);
        // console.log(combo_arr);
        var combo_data = [];
        for (var i = 0; i < combo_arr.length; i++) {
            combo_data.push({
                'id': combo_arr[i],
                'text': combo_arr[i]
            })
        }
        mini.get('right' + data.c_id).setData(combo_data);

    } else if (data.type.indexOf('buttonedit') > -1) {// 参照
        mini.get('right' + data.c_id).on("buttonclick", function (e) {
            var Ref = $.parseJSON(data.ref);
            mini.open({
                url: bootPATH + "../frame/frame1/pages/formDesign/selectRef.html",
                title: "请选择",
                onload: function () { // 弹出页面加载完成
                    var iframe = this.getIFrameEl();
                    var SetData = {};
                    if (data.cTableField == "parent_level") {// 父级id
                        SetData = {
                            ref: {
                                formListId: formId
                            },
                            menusFormTypes: menusFormTypes,
                            menuId: menuId
                        };
                    } else {
                        SetData = {
                            ref: Ref.ref,
                            menuId: menuId,
                            menusFormTypes: menusFormTypes,
                        };
                        reSelectFlag = true;
                    }
                    iframe.contentWindow.SetData(SetData);
                },
                ondestroy: function (action) { // 弹出页面关闭前
                    if (action == "ok") {
                        var iframe = this.getIFrameEl();
                        var RefData = iframe.contentWindow.onTableOk();
                        RefData = mini.clone(RefData);
                        console.log(RefData, 'selectRef');
                        var refKeyArr = [];
                        var refKey = '';
                        for(var key in RefData){
                            refKeyArr.push(key);
                        }
                        refKey = refKeyArr[0];
                        refKey = refKey.split('_')[0] + '_id';
                        console.log(refKey,RefData[refKey]);

                        // console.log(Ref.ref.cTableField);
                        // console.log(RefData[Ref.ref.cTableField]);
                        if (data.cTableField == "parent_level") {// 父级id
                            mini.get('right' + data.c_id).setText(RefData[mTableName + '_name']);
                            if (RefData.mTableId == undefined) {
                                mini.get('right' + data.c_id).setValue(RefData[mTableName + '_id']);
                            } else {
                                mini.get('right' + data.c_id).setValue(RefData.mTableId);
                            }
                            mini.get('right' + data.c_id).doValueChanged();
                        } else {
                            // mini.get('right'+ data.c_id).setValue(RefData[Ref.ref.cTableField]);
                            mini.get('right' + data.c_id).setText(RefData[Ref.ref.cTableField]);
                            var newMTableName = Ref.ref.cTableName;
                            mini.get('right' + data.c_id).setValue(RefData[newMTableName + '_id']);
                            mini.get('right' + data.c_id).doValueChanged();

                        }
                        if (reSelectFlag) {// 重新选择了参照
                            // for(var p=0;p<complex_add_fields.length;p++) {
                            for (var item in complex_add_values) {
                                var name = $.parseJSON(data.ref).ref.cTableName;
                                if (item.indexOf($.parseJSON(data.ref).ref.cTableName) > -1) {
                                    complex_add_values[item] = RefData[name + '_id'];
                                }
                            }
                            // }
                            // complex_add_value = RefData.id;
                        }
                    }
                }
            })
        })
    } else {// 文本类设置长度限制
        if (data.cLength != '') {
            mini.get('right' + data.c_id).setMaxLength(data.cLength);
        }
    }
}
var updateRowData={};
function create_table(arr_table, area) {

    arr_table = jsonByGroup(arr_table);// 表格按数据库表名分组
    console.log(arr_table, 'arr_table分组后');

    for (var i = 0; i < arr_table.length; i++) {
        // arr_table[i]是一个表格
        var id = arr_table[i].c_id;
        idyhy=mini.clone(id);
        var type = arr_table[i].type;
        var mTableName = arr_table[i].cTableName;
        var cols = JSON.parse(arr_table[i].gridColumns);
        var data = arr_table[i].data;
        // var grid = new mini.DataGrid();//js创建表格

        // var tree_data = [];
        for (var r = 0; r < cols.length; r++) {

            console.log(cols[r].columns);
            if (cols[r].columns == undefined) {// 无分组
                // tree_data.push(cols[r]);
                cols[r] = setEditor(cols[r]);
                console.log(cols[r].columns);
            } else {
                var cols2 = cols[r].columns;
                for (var s = 0; s < cols2.length; s++) {
                    if (cols2[s].columns == undefined) {// 一层分组
                        // tree_data.push(cols2[s]);
                        cols2[s] = setEditor(cols2[s]);
                    } else {
                        var cols3 = cols2[s].columns;
                        for (var t = 0; t < cols3.length; t++) {
                            // tree_data.push(cols3[t]);
                            cols3[t] = setEditor(cols3[t]);
                        }
                    }
                }
            }
        }
        console.log(cols, '整理分组');

        // 个性化
        function setEditor(col) {

            // 表格单元格验证
            console.log(data);
            console.log(col);

            for (var x = 0; x < data.length; x++) {
                if (col.field == data[x].col_id) {
                    if (data[x].cNull == 'true') {// 必填
                        if (data[x].cRequire == 'true') {// 验证
                            col.vtype = "required;" + data[x].cRequire;
                        } else {// 验证
                            col.vtype = "required";
                        }
                    } else {// 非必填
                        if (data[x].cRequire == 'none') {// 不验证

                        } else {// 验证
                            col.vtype = "" + data[x].cRequire;
                        }
                    }

                    var parse = JSON.parse(data[x].cRefObj);
                    console.log(JSON.parse(data[x].cRefObj));
                    console.log(parse.disable);
                    if(parse.disable != 'undefined') {
                        //当disable的字段为true时给控件加禁止编辑属性
                        if(parse.disable == 'true'){
                            if (col.editor.type == 'combobox') {// 这一列是下拉框

                                // 设置下拉内容
                                var combo_data = [];
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id) {
                                        var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
                                        console.log(combo_arr);
                                        combo_data = [];
                                        for (var p = 0; p < combo_arr.length; p++) {
                                            combo_data.push({
                                                'id': combo_arr[p],
                                                'text': combo_arr[p]
                                            })
                                            console.log(combo_data);
                                        }
                                    }
                                }
                                col.editor = {
                                    data: combo_data,
                                    type: col.editor.type
                                };

                            } else if (col.editor.type == 'datepicker') {

                                if (type == 'tab_table' || type == 'table') {
                                    col.editor = {
                                        type: col.editor.type
                                    };
                                }
                                // 格式化
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id) {
                                        col.dateFormat = data[k].cFormat;
                                        // 默认设置当前日期
                                        if (data[k].cDateDefault == 'true') {
                                            datepick_child.push(data[k]);

                                        }
                                    }
                                }
                            } else if (col.editor.type == 'buttonedit') {

                                if (type == 'tab_table' || type == 'table') {
                                    col.editor = {
                                        type: col.editor.type
                                    };
                                }
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id) {
                                        // 弹窗
                                        col.editor.onbuttonclick = "onSelectRef(" + id + ","
                                            + data[k].ref + ")";
                                    }
                                }
                            } else if (col.editor.type == 'tab_table') {

                                col.editor = {
                                    type: col.editor.type
                                };

                            } else {// 文本类组件
                                col.editor = {
                                    type: col.editor.type
                                };
                                // 设置长度限制
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id && data[k].cLength != 0) {
                                        col.editor.maxLength = data[k].cLength;
                                    }
                                }
                            }

                        }
                        else if(parse.disable == 'false'){
                            delete(col.editor);
                        } else {
                            // col.editor.type = col.type;
                            col.editor = {
                                type: col.editor.type
                            };
                            if (col.editor.type == 'buttonedit') {
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id) {
                                        // 弹窗
                                        col.editor.onbuttonclick = "onSelectRef(" + id + ","
                                            + data[k].ref + ")";
                                    }
                                }
                            }
                            else if (col.editor.type == 'datepicker') {
                                // 格式化
                                for (var k = 0; k < data.length; k++) {
                                    if (col.field == data[k].col_id) {
                                        col.dateFormat = data[k].cFormat;
                                        // 默认设置当前日期
                                        if (data[k].cDateDefault == 'true') {
                                            datepick_child.push(data[k]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else {
                        if (col.editor.type == 'datepicker') {

                            if (type == 'tab_table' || type == 'table') {
                                col.editor = {
                                    type: col.editor.type
                                };
                            }
                            // 格式化
                            for (var k = 0; k < data.length; k++) {
                                if (col.field == data[k].col_id) {
                                    col.dateFormat = data[k].cFormat;
                                    // 默认设置当前日期
                                    if (data[k].cDateDefault == 'true') {
                                        datepick_child.push(data[k]);

                                    }
                                }
                            }
                        }
                        else if(col.editor.type == 'buttonedit') {
                            col.editor = {
                                type: col.editor.type
                            };
                            for (var k = 0; k < data.length; k++) {
                                if (col.field == data[k].col_id) {
                                    // 弹窗
                                    col.editor.onbuttonclick = "onSelectRef(" + id + ","
                                        + data[k].ref + ")";
                                }
                            }
                        }
                    }
                }
            }


            // if (col.editor.type == 'combobox') {// 这一列是下拉框
            //
            //     // 设置下拉内容
            //     var combo_data = [];
            //     for (var k = 0; k < data.length; k++) {
            //         if (col.field == data[k].col_id) {
            //             var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
            //             console.log(combo_arr);
            //             combo_data = [];
            //             for (var p = 0; p < combo_arr.length; p++) {
            //                 combo_data.push({
            //                     'id': combo_arr[p],
            //                     'text': combo_arr[p]
            //                 })
            //                 console.log(combo_data);
            //             }
            //         }
            //     }
            //     col.editor = {
            //         data: combo_data,
            //         type: col.editor.type
            //     };
            //
            // } else if (col.editor.type == 'datepicker') {
            //
            //     if (type == 'tab_table') {
            //         col.editor = {
            //             type: col.editor.type
            //         };
            //     }
            //     // 格式化
            //     for (var k = 0; k < data.length; k++) {
            //         if (col.field == data[k].col_id) {
            //             col.dateFormat = data[k].cFormat;
            //             // 默认设置当前日期
            //             if (data[k].cDateDefault == 'true') {
            //                 datepick_child.push(data[k]);
            //
            //             }
            //         }
            //     }
            // } else if (col.editor.type == 'buttonedit') {
            //
            //     if (type == 'tab_table') {
            //         col.editor = {
            //             type: col.editor.type
            //         };
            //     }
            //     for (var k = 0; k < data.length; k++) {
            //         if (col.field == data[k].col_id) {
            //             // 弹窗
            //             col.editor.onbuttonclick = "onSelectRef(" + id + ","
            //                 + data[k].ref + ")";
            //         }
            //     }
            // } else if (col.editor.type == 'tab_table') {
            //
            //     col.editor = {
            //         type: col.editor.type
            //     };
            //
            // } else {// 文本类组件
            //     col.editor = {
            //         type: col.editor.type
            //     };
            //     // 设置长度限制
            //     for (var k = 0; k < data.length; k++) {
            //         if (col.field == data[k].col_id && data[k].cLength != 0) {
            //             col.editor.maxLength = data[k].cLength;
            //         }
            //     }
            // }
            // // 表格单元格验证
            // console.log(data);
            // console.log(col);
            // for (var x = 0; x < data.length; x++) {
            //     if (col.field == data[x].col_id) {
            //         if (data[x].cNull == 'true') {// 必填
            //             if (data[x].cRequire == 'true') {// 验证
            //           col.vtype = "required;" + data[x].cRequire;
            //             } else {// 验证
            //                 col.vtype = "required";
            //             }
            //         } else {// 非必填
            //             if (data[x].cRequire == 'none') {// 不验证
            //
            //             } else {// 验证
            //                 col.vtype = "" + data[x].cRequire;
            //             }
            //         }
            //
            //         var parse = JSON.parse(data[x].cRefObj);
            //         console.log(JSON.parse(data[x].cRefObj));
            //         console.log(parse.disable);
            //         if(parse.disable) {
            //             //当disable的字段为true时给控件加禁止编辑属性
            //             if(parse.disable=="true"){
            //
            //             }else if(parse.disable=="false"){
            //                 col.enabled = 'false';
            //             }
            //         }
            //     }
            // }
            return col;
        }

        // for(var j=0;j<cols.length;j++) {
        // if(cols[j].editor.type == 'combobox') {//这一列是下拉框
        //
        // //设置下拉内容
        // var combo_data = [];
        // for(var k=0;k<data.length;k++) {
        // if(cols[j].name == data[k].col_id) {
        // var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
        // combo_data = [];
        // for(var p=0;p<combo_arr.length;p++) {
        // combo_data.push({
        // 'id':combo_arr[p],'text':combo_arr[p]
        // })
        // }
        // }
        // }
        // cols[j].editor = {data:combo_data,type:cols[j].editor.type};
        //
        // // if(type == 'table') {
        // // var editortype = cols[j].editor.type;
        // // var editordata = cols[j].editor.data;
        // // cols[j].editor = {type: editortype, data: editordata};
        // //// cols[j].editor.data = cols[j].editor.data;
        // // }else {
        // // for(var k=0;k<data.length;k++) {
        // // if(cols[j].name == data[k].col_id) {
        // // var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
        // // var combo_data = [];
        // // for(var p=0;p<combo_arr.length;p++) {
        // // combo_data.push({
        // // 'id':combo_arr[p],'text':combo_arr[p]
        // // })
        // // }
        // // }
        // // }
        // // cols[j].editor = {data:combo_data,type:cols[j].editor.type};
        // // }
        //
        // }else if(cols[j].editor.type == 'datepicker') {
        //
        // if(type == 'tab_table') {
        // cols[j].editor = {type:cols[j].editor.type};
        // }
        // //格式化
        // for(var k=0;k<data.length;k++) {
        // if(cols[j].name == data[k].col_id) {
        // cols[j].dateFormat = data[k].cFormat;
        // //默认设置当前日期
        // if(data[k].cDateDefault == 'true') {
        // datepick_child.push(data[k]);
        // // cols[j].defaultValue = new Date();
        // }
        // }
        // }
        //
        // }else if(cols[j].editor.type == 'buttonedit') {
        //
        // if(type == 'tab_table') {
        // cols[j].editor = {type:cols[j].editor.type};
        // }
        // for(var k=0;k<data.length;k++) {
        // if(cols[j].name == data[k].col_id) {
        // //弹窗
        // cols[j].editor.onbuttonclick = "onSelectRef("+id+","+data[k].ref+")";
        // }
        // }
        //
        //
        // }else if(cols[j].editor.type == 'tab_table') {
        //
        // cols[j].editor = {type:cols[j].editor.type};
        //
        // }else {//文本类组件
        //
        // cols[j].editor = {type:cols[j].editor.type};
        // //设置长度限制
        // for(var k=0;k<data.length;k++) {
        // if(cols[j].name == data[k].col_id && data[k].cLength != 0) {
        // cols[j].editor.maxLength = data[k].cLength;
        // }
        // }
        // }
        // //表格单元格验证
        // for(var x=0;x<data.length;x++) {
        // if(cols[j].name == data[x].col_id) {
        // if(data[x].cNull == 'true') {//必填
        // if(data[x].cRequire == 'none') {//不验证
        // cols[j].vtype="required";
        // }else {//验证
        // cols[j].vtype="required;"+data[x].cRequire;
        // }
        // }else {//非必填
        // if(data[x].cRequire == 'none') {//不验证
        //
        // }else {//验证
        // cols[j].vtype=""+data[x].cRequire;
        // }
        // }
        // }
        // }
        // }
        var $clone = "    <div  id='dg"
            + id
            + "'>\n"
            + "        <div class='mini-toolbar' style='border-bottom:0;padding:0px;'>\n"
            + "            <table style='width:100%;'>\n"
            + "                <tr>\n"
            + "                    <td style='width:100%;'>\n"
            + "                        <a class='mini-button' iconCls='icon-add' onclick='onAddRow(e,"
            + id
            + ")' plain='true'>新增行</a>\n"
            + "                        <a class='mini-button' iconCls='icon-remove' onclick='onRemoveRow(e,"
            + id + ")' plain='true'>删除行</a>\n"
            +"                        <a class='mini-button' iconCls='icon-remove' onclick='onCompute(e,"
            + id + ")' plain='true'>计算</a>\n"
            + "                     </td>\n" + "                    \n"
            + "                </tr>\n"
            + "            </table>           \n" + "        </div>"

        $clone += "<div id='" + id + "' class='mini-datagrid mtable-"
            + mTableName + "' style=''\n>" + " contextMenu='#gridMenu" + id
            + "'>\n" + "    <div property='columns'></div>\n"
            + "</div></div>";

        var gridMenu = "<ul  id='gridMenu"
            + id
            + "' class='mini-contextmenu'  onbeforeopen='onBeforeOpenGrid(e,"
            + id
            + ")'>\n"
            + "   <li name='add' iconCls='icon-add' onclick='onAddRow(e,"
            + id
            + ")'>增行</li>\n"
            + "   <li name='remove' iconCls='icon-remove' onclick='onRemoveRow(e,"
            + id + ")'>删行</li>\n" + "</ul>";

        if (area == 'tab') {
            var tabs = mini.get(data[i].tabs_id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,// 整个页签
                tab_id: data[i].tab_id
                // 插入的当前页签
            }
            // grid.render(document.getElementById(tabEl.id));

            var field = escapeJquery(tabEl.id);
            $("#" + field).append($clone);
            $("#" + field).append(gridMenu);

        } else {
            // grid.render(document.getElementById("formField"));

            $("#formField").append($clone);
            $("#formField").append(gridMenu);
        }
        mini.parse();
        var grid = mini.get(id);
        console.log(cols, 'cols');
        grid.set({
            url: "",
            columns: cols,
            // multiSelect:true,
            allowResize: true,
            allowCellEdit: true,
            allowCellSelect: true,
            cellEditAction: "celldblclick",
            allowRowSelect: true,
            showPager: false,
            editNextOnEnterKey: true,
            editNextRowCell: true,
            showModified: false,
            allowCellValid: true,

            // allowRowSelect:false,
            // enableHotTrack:false,
        });
        $("#dg" + id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 100,
            top: arr_table[i].iConY,
            left: arr_table[i].iConX,
            position: "absolute"
        });
        $("#" + id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 70
        });
        grid.setData([]);
        new CopyExcel(grid); // Excel互操作插件
        mini.parse();
        addRow(id);// 回车增加一行
        mini.get(id).on('resize', function (e) {
            console.log(e);
            $("#dg" + id).css({
                width: e.sender.width,

            });
        });
        mini.get(id).on('cellbeginedit', function (e) {
            // console.log(e.sender);
            currentCell = e;
            // e.row['round'] = '123';

        });
        var cMath; // 子表公式
        mini.get(id).on('drawCell', function (e) {
                console.log('进入绘制单元格');
                // e.sender.id//表格id
                var data;
                for (var o = 0; o < arr_table.length; o++) {
                    if (arr_table[o].c_id == e.sender.id) {
                        data = arr_table[o].data;
                    }
                }
                for (var p = 0; p < data.length; p++) {
                    if (data[p].cTableField == e.field) {
                        cMath = $.parseJSON(data[p].cMath).newStrEn;
                    }
                }

                console.log(cMath, '公式');
                var str = cMath;
                console.log(str, "str");
                if (cMath != '' && cMath != undefined) {

                    var param = setLinkage(e, cMath, str, 'table');
                    str = param.str;
                    var mathType = param.mathType;
                    var linkType = param.linkType;
                    var linkId = param.linkId;// 关联类型设置的id
                    var grid = mini.get(e.sender.id);
                    if (mathType == 'mathType_other') {// 计算/拼接
                        var thisStr = str.split('=')[0];
                        if (currentCell != undefined) {
                            if (thisStr.indexOf(currentCell.field) == -1
                                || linkType.indexOf('base') > -1) {
                                var result = evil(str);
                                console.log(result);
                                console.log(!isNaN(result));

                                if (result != undefined && result != '$') {
                                    e.cellHtml = result;
                                    e.row[e.field] = result;

                                     var curCell =mini.get(id).getCurrentCell();
                                     var rowData = {};
                                     rowData[curCell[1].field] =
                                     curCell[0][curCell[1].field];
                                     mini.get(id).updateRow(e.row,
                                     rowData);
                                     console.log(mini.get(id).getCurrentCell());
                                     var curCell = mini.get(id).getCurrentCell();
                                     e.row[curCell[1].field] =
                                     curCell[0][curCell[1].field];
                                }
                            }
                        }
                         } else if (mathType == 'mathType_link') {// 关联

                         if (str.fileldValue != undefined) {
                             console.log(str);
                         	$.ajax({
                         		type : 'POST',
                         		url : ajaxUrl + '/formltems/casacade.do ',
                         		dataType : 'json',
                                data: JSON.stringify(str),
                         		success : function(data) {
                        			// e.cellHtml = data.data;
                        			// e.row[e.field] = data.data;
                         			var up = {};
                        			up[e.field] = 'cs';
                        			mini.get(e.sender.id).updateRow(e.row,
                        					up);
                        		},
                         		error : function(jqXHR, textStatus,
                         				errorThrown) {
                         			alert('失败！');
                         		}
                         	})// ajax
                         }
                    }
                    else if (mathType == 'mathType_StandardAmount') {
                        mini.formatDate(str.beginTime,'yyyy-MM-dd'),
                        mini.formatDate(str.endTime,'yyyy-MM-dd'),
                        console.log("开始获取报销标准金额");
                        console.log("str",str);
                        $.ajax({
                            type: 'POST',
                            url:ajaxUrl + '/sqlAction/findStandardAmount.do',
                            dataType: 'json',
                            contentType: "application/json",
                            data: JSON.stringify(str),
                            success: function (data) {
                                console.log("报销标准",data.data)
                                e.cellHtml = data.data;
                                e.row[e.field] = data.data;
                                // var nowRow = grid.getSelected();
                                // var eRows =  e.row;
                                // updateRowData = eRows;
                                // if(e.value == data){
                                //     console.log('是');
                                // }else{
                                //     //如果不是更新行
                                //     grid.updateRow(nowRow, updateRowData);
                                // }
                            }
                        })
                    }
                    else if (mathType == 'mathType_day') { // 通过日期计算天数
                        console.log("进入天数计算");
                        //console.log(dayState,'时间计算状态码');
                        console.log(str,'天数');
                        // e.cellHtml = '2';
                        // e.row[e.field] = '2';
                        // //原来的
                        // var nowRow = grid.getSelected();
                        // //新的
                        // var eRows =  e.row;
                        // updateRowData = eRows;
                        // //更新行
                        // grid.updateRow(nowRow, updateRowData);
                        $.ajax({
                            type: 'POST',
                            url: ajaxUrl + '/sqlAction/day.do',
                            dataType: 'json',
                            contentType: "application/json",
                            data: JSON.stringify(str),
                            success: function (data) {
                                console.log(data);

                                // var up = {};
                                // up[e.field] = data;

                                e.cellHtml = data;
                                e.row[e.field] = data;
                                var nowRow = grid.getSelected();
                                var eRows =  e.row;
                                updateRowData = eRows;
                                for(var k in updateRowData){
                                    if(updateRowData[k] == NaN){
                                        updateRowData[k] = '';
                                    }
                                }
                                //dayState = '';
                                //判断value的值是否是返回值，如果有就不更新，如果没有就更新
                                if(e.value == data){
                                    console.log('是');
                                }else{
                                    //如果不是更新行
                                    grid.updateRow(nowRow, updateRowData);
                                }
                                //grid.updateRow(nowRow, updateRowData);

                            }
                        })

                    }
                    else if (mathType == 'mathType_cascade') { //级联
                        console.log("进入级联计算");
                        console.log(str, "str级联计算");
                        $.ajax({
                                type: 'POST',
                                url: ajaxUrl + '/formltems/casacade.do ',
                                dataType: 'json',
                                contentType: "application/json",
                                data: JSON.stringify(str),
                                success: function (data) {
                                    console.log(data);
                                    if (data.state == 'success') {
                                        var casa = data.data;
                                        console.log("casa:", casa[0]);
                                        // var casaJson = casa[0];
                                        var up = {};
                                        up[e.field] = data.vale;
                                        // var value = casaJson[returnFileld];
                                        console.log("value", data.vale);
                                        // e.cellHtml = data.vale;
                                        e.cellHtml = data.vale;
                                        e.row[e.field] = data.vale;
                                        var nowRow = grid.getSelected();
                                        var eRows =  e.row;
                                        updateRowData = eRows;
                                        //grid.updateRow(nowRow, updateRowData);
                                    }
                                },
                                error: function () {

                                }
                            }
                        )
                    }
                    else if (mathType == 'mathType_code') {
                        console.log("进入编码计算规则");
                        var now = new Date();
                        console.log("str:" + str);
                        var year = now.getFullYear();
                        var month = now.getMonth();
                        if (month < 10) month = "0" + ( month + 1);
                        var date = now.getDate();
                        if (date <10) date = "0" + date;
                        var nowYmd = year +""+ month +""+ date +"";
                        console.log("进入编码规则设置",nowYmd);

                    }
                    else if(mathType == "mathType_findTableSum"){

                        console.log("子表进入跨表求和str:" + str);
                        $.ajax({
                            url : ajaxUrl + '/sqlAction/findTableSum.do',
                            type : 'post',
                            dataType: 'json',
                            contentType: "application/json",
                            data: JSON.stringify(str),
                            success : function (data) {
                                console.log("跨表求和data",data)
                                if (data.state == "success"){
                                    var vale ;
                                    if(data.data == ""){
                                        vale = null;
                                    }else{
                                        vale = data.data;
                                    }
                                    var up = {};
                                    up[e.field] = vale;
                                    console.log("value", vale);
                                    // e.cellHtml = data.vale;
                                    e.cellHtml = vale;
                                    e.row[e.field] = vale;
                                }else{
                                    mini.alert(data.message);
                                }
                            },
                            error : function (data) {

                            }
                        })


                    }
                    else if(mathType == "mathType_if"){
                        console.log("进入子表if公式");

                        // $.ajax({
                        //     url  :  ajaxUrl + '/sqlAction/findFormState.do',
                        //     type : 'post',
                        //     data : JSON.stringify(str),
                        //     dataType : 'json',
                        //     contentType: "application/json",
                        //     success : function (data) {
                        //         console.log("跨表求和data",data)
                        //         if (data.state == "success"){
                        //             var vale ;
                        //             if(data.data == ""){
                        //                 vale = null;
                        //             }else{
                        //                 vale = data.data;
                        //             }
                        //             var up = {};
                        //             up[e.field] = vale;
                        //             console.log("value", vale);
                        //             // e.cellHtml = data.vale;
                        //             e.cellHtml = vale;
                        //             e.row[e.field] = vale;
                        //         }else{
                        //             mini.alert(data.message);
                        //         }
                        //     },
                        //     error : function (data) {
                        //
                        //     }
                        // })




                    }
                }
                else{
                    console.log('编辑本次冲抵金额时');
                    //可用金额
                    var usePrice = '';
                     if(e.field == ('DetailsOffsetReserveGoods_xgry_0008')){
                         //本次冲抵金额
                         var nowPrice = e.value;
                         if(edit_data.DetailsOffsetReserveGoods){
                             //可用金额
                             usePrice = edit_data.DetailsOffsetReserveGoods[0]['DetailsOffsetReserveGoods_xgry_0003'];
                         }else{
                             var gridPrice = mini.get(id);
                             var gridPriceData = gridPrice.getSelected();
                             if(gridPriceData){
                                usePrice = gridPriceData['DetailsOffsetReserveGoods_xgry_0007'];
                                console.log(usePrice);
                            }

                         }
                         if(nowPrice){
                             if(usePrice){
                                 //如果本次冲抵金额大于可用金额，提示不可以
                                 if(parseInt(nowPrice) > parseInt(usePrice)){
                                     mini.alert('本次冲抵金额不可大于可用金额,请修改');
                                 }
                             }
                         }
                     //如果字段为出行方式

                     }
                     else if(e.field=="DetailsOfReimbursementForAccommodationExpenses_xgry_0005" || e.field=="TravelSubsidy_xgry_0004"){
                       if(e.field=="DetailsOfReimbursementForAccommodationExpenses_xgry_0005") {
                           var cityName = e.value;
                           console.log(cityName);
                           if (cityName) {
                               $.ajax({
                                   url: ajaxUrl + '/trip/finds.do',
                                   type: 'POST',
                                   data: {
                                       Name: cityName
                                   },
                                   success: function (data) {
                                       console.log(data.Provinces_name);
                                       //备份原来选择的城区
                                       var oldCityName = e.row['DetailsOfReimbursementForAccommodationExpenses_xgry_0004'];
                                       //新选择的赋值
                                       e.row['DetailsOfReimbursementForAccommodationExpenses_xgry_0004']=data.Provinces_name;
                                       var grid2 = e.sender;
                                       console.log(grid2);
                                       if(e.row['DetailsOfReimbursementForAccommodationExpenses_xgry_0004'] != oldCityName){
                                           grid2.updateRow(e.row,e.row);
                                       }else{
                                           console.log('赋值');
                                       }



                                   }
                               })

                           }
                       }
                       else {
                           var cityName = e.value;
                           console.log(cityName);
                           if (cityName) {
                               $.ajax({
                                   url: ajaxUrl + '/trip/finds.do',
                                   type: 'POST',
                                   data: {
                                       Name: cityName
                                   },
                                   success: function (data) {
                                       console.log(data);
                                       var oldCityName=e.row['TravelSubsidy_xgry_0003'];
                                       e.row['TravelSubsidy_xgry_0003']=data.Provinces_name;
                                       var grid2 = e.sender;
                                       console.log(grid2);
                                       if(e.row['TravelSubsidy_xgry_0003']!=oldCityName){
                                           grid2.updateRow(e.row,e.row);
                                       }


                                   }
                               })

                           }
                       }
                     }
                     else if(e.field == "DetailsOfTransportationCosts_xgry_0001"){
                        //获取当前当前单据的申请人
                         //var mainFormData = getForm();
                         //var applyPerson = mainFormData[formSh.cTableName + '_single_person'];
                         var applyPerson = userInfoObj.userName;
                         console.log(applyPerson);
                         //获取选择的出行方式
                         var goWay = e.value;
                         //判断是否选择了出行方式
                         if(goWay){
                             //如果选择了，就请求出行方式是否允许
                             $.ajax({
                                 url: ajaxUrl + '/trip/findall.do',
                                 type: 'POST',
                                 data: {
                                     Name:applyPerson,
                                     TName:goWay
                                 },
                                 success: function (data) {
                                     console.log(data);
                                     if(data.fail!=undefined){
                                         mini.alert(data.fail,'系统提示',function (action) {
                                             if(action == 'ok'){
                                                 e.row['DetailsOfTransportationCosts_xgry_0001'] = '';
                                                 if(e.value == ''){
                                                     console.log('是');
                                                 }else{
                                                     var grid2 = e.sender;
                                                     console.log(grid2);
                                                     grid2.updateRow(e.row,e.row);
                                                 }
                                             }
                                         });
                                     }

                                 },
                                 error: function (data) {
                                     console.log('请求失败')
                                 }
                             })
                         }else{
                            console.log('没选择出行方式不请求');
                         }

                     }
                }
            })
        // 子表列求和公式
        mini.get(id).on('cellendedit', function (e) {
                    for (var m = 0; m < arr_cMath_main.length; m++) {
                        var str = arr_cMath_main[m].math;
                        if (str != '' && str != undefined) {
                            if (arr_cMath_main[m].math
                                .indexOf('sumCols(') > -1) {
                                var param = setLinkage(e,
                                    arr_cMath_main[m].math,
                                    arr_cMath_main[m].math, 'table');
                                if (param.sumColsValue != undefined) {
                                    mini
                                        .get(
                                            'right'
                                            + param.sumColsField)
                                        .setValue(
                                            param.sumColsValue);
                                }
                            }
                        }
                    }
                })
        // mini.get(id).on("cellendedit", function (e) {
        // console.log(e);
        // console.log(e.column,'所在列');
        // console.log(e.field,'列字段');
        // console.log(e.row,'行数据');
        // console.log(data[0].c_id,'表格id');
        // for(var p=0;p<data.length;p++) {
        // if(data[p].cTableField == e.field){
        // cMath = $.parseJSON(data[p].cMath).newStrEn;
        // }
        // }
        //
        // console.log(cMath,'公式');
        // var str = cMath;
        // if(cMath != '' && cMath != undefined) {
        // // $.each(cMath.match(/[^\[]+(?=\])/g), function(i, word) {
        // // console.log(i, word);
        // // var value;
        // // if(i>0) {//等式右侧
        // // for(var i=0;i<component_data.length;i++) {
        // // if(component_data[i].cTableField == word) {
        // //
        // // if(component_data[i].type == 'table') {//变量是表格类型
        // // var mathCol_data = mini.get(component_data[i].c_id).getData();
        // // console.log(mathCol_data);
        // // for(var n=0;n<mathCol_data.length;n++) {
        // // if(mathCol_data[n][word] != undefined &&
        // mathCol_data[n]._id==e.row._id) {
        // // value = mathCol_data[n][word];
        // // }
        // // }
        // //
        // // }else {
        // // value = mini.get('right'+component_data[i].c_id).getValue();
        // // }
        // // var pattern = '\\['+word+'\\]';
        // // str = str.replace(new RegExp(pattern,'g'),value);
        // // }
        // // }
        // // }
        // // });
        // // console.log(str,'str');
        // str = setLinkage(e,cMath,str);
        // console.log(evil(str));
        // var row = {};
        // row[e.field] = evil(str);
        // console.log(e.row,'e.row');
        // console.log(row,'更新row');
        // // console.log(mini.get(id).getSelected())
        // // console.log(mini.get(id).getRowByUid(row._uid))
        // console.log(mini.get(id).getCurrentCell());
        //
        // // mini.get(id).cancelEdit();
        // // mini.get(id).cancelEditRow(e.row);
        // // mini.get(id).updateRow(e.row,
        // {orderLimeted_child:'000',orderType_child:'888'});//here
        // if(evil(str) == '$') {
        //
        // }else {
        // mini.get(id).updateRow(e.row, row);//here
        // }
        // }
        // });

    }// 每个arr[i]是一个表格
}

function create_tab(arr_tab) {

    arr_tab = jsonByGroup(arr_tab);// 表格按数据库表名分组
    console.log(arr_tab, 'arr_tab分组后');
    for (var i = 0; i < arr_tab.length; i++) {
        // arr_table[i]是一个表格
        var id = arr_tab[i].c_id;
        var data = arr_tab[i].data;
        var div = '';
        for (var j = data.length - 1; j >= 0; j--) {
            div = "<div name='" + data[j].tab_id + "' title='"
                + data[j].cTabText + "'> </div>\n" + div;
        }

        var $clone = "<div id='" + id + "'class='mini-tabs' activeIndex='0'>\n"
            + div + "</div>";
        $('#formField').append($clone);
        mini.parse();
        $("#" + id).css({
            width: data[0].iWidth,
            height: data[0].iLabHeight,
            "min-height": 100,
            top: data[0].iConY,
            left: data[0].iConX,
            position: "absolute"
        });
    }

}

// 参照生单
function openRef(data) {
    var formListId;
    $.ajax({
        url: ajaxUrl +'/rule/findFormListIdByCtableName.do',
        type: 'POST',
        data: {
            ruleId:data
        },
        success: function (data) {
            formListId = data.formListId;
        },
        error: function (data) {
            console.log('请求失败')
        }
    })
    mini.open({
        url: bootPATH
            + "../frame/frame1/pages/reference/selectFormReference.html",
        title: "选择参照",
        width: 850,
        height: 500,
        onload: function () { // 弹出页面加载完成
            var iframe = this.getIFrameEl();
            iframe.contentWindow.SetData(formListId,data);
        },
        ondestroy: function (action) { // 弹出页面关闭前
            if (action == "ok") { // 如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();   //把子页面的方法带过来
                data = mini.clone(data);

                dataer=mini.clone(data);                    //紧接着下面要打点用
                console.log(dataer);
                stable=dataer.stable;
                row1=dataer.row1;//打点调用子页面传来的参数字符串row3
                ruleId=dataer.ruleId;                        //打点调用子页面传来的参数字符串ruleId
                console.log(row1);
                console.log(stable);
                console.log(ruleId);
                var str={};
                str.stable=stable;
                str.row1=row1;
                console.log(str);
                str=JSON.stringify(str);
                $.ajax({
                    url:ajaxUrl + "/rule/RefToPage.do",
                    type:"post",
                    data:{
                        ruleId:ruleId,
                        str:str
                    },
                    success:function (data) {
                        console.log(data);
                        formRefData2=mini.clone(data)

                            formRefData =mini.clone(data) ;        //准备下面要用到
                        formRefData6=mini.clone(data[0]);



                    },
                    error:function (data) {
                        console.log(data);
                    }
                })
                data = mini.clone(data);
                console.log(data, '----');

                var formField = $("#formField").children();   //所有子节点
                console.log(formField, 'formField');

                $.ajax({
                    url: ajaxUrl + "/rule/findRefByModelId.do?fromListId=" + formId,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        var relationRef = data.data;
                        console.log(relationRef, 'relationRef 参照生单对照关系');
                        for (var i = 0; i < formField.length; i++) {
                            // console.log(formField[i].id, 'id');

                            if (formField[i].className == 'form_items') {// 主表组件

                                var form = new mini.Form("formField");  //准备form属性
                                    var codingData=form.getData();     //直接获取表单上的数据
                                    // console.log(codingData);

                              Object.assign(codingData,formRefData6);    //assign方法{}里面有则替换，没有则加进去

                                console.log(formRefData);
                                form.setData(codingData);               //在保持原来的数据不变情况下，加进参照的

                                // if (formField[i].id.indexOf('buttonedit' > -1)) {// 参照赋值
                                //     for (var item in formRefData.rows1[0]) {
                                //         var setBE = formRefData.rows1[0];
                                //         console.log(formField[i].getAttribute('name'));
                                //         //getAttribute为单据本有字段，item为参照单据的字段
                                //         // sourceField: "orderMumber"
                                //         // targetField: "ft_code"
                                //         for (var j = 0; j < relationRef.length; j++) {
                                //             if (relationRef[j].sourceField == item) {
                                //                 if (relationRef[j].targetField == formField[i].getAttribute('name')) {
                                //                     mini.get("right" + formField[i].id)
                                //                         .setText(setBE[item]);
                                //                 }
                                //             }
                                //         }
                                //     }
                                // }

                            } else {// 表格
                                if (formField[i].className.indexOf('mini-menu') == -1) {
                                        var grid=mini.get(idyhy);
                                    formRefData=JSON.stringify(formRefData);//  从这到下面都是为了获取grid这个id
                                    console.log(formRefData);
                                    formRefData= intercept(formRefData,0)
                                    console.log(formRefData);
                                    formRefData=intercept2(formRefData,1);
                                    console.log(formRefData);
                                    formRefData= intercept(formRefData,0)
                                    console.log(formRefData);
                                    // var formRefData="datagrid_DetailsOfServiceFeePayee"
                                    var formRefData3="datagrid_";
                                    var formRefData4=formRefData3+formRefData;
                                    console.log(formRefData4);
                                   var grid= mini.get(formRefData4);
                                    console.log(grid);                       //从后端查出来的数据来拼接获取id



                                    // var grid = mini.get(formField[i].id
                                    //     .match(/dg(\S*)/)[1]);
                                    // console.log(grid);
                                    // grid.setData("");
                                    // var temp =
                                    // formField[i].childNodes[2].className.split('
                                    // ');
                                    if (formRefData==[]) {

                                    } else {
                                        var rows2 = formRefData2;  //获取表格要加的那一行数据
                                        if(grid!=undefined){
                                            for(let i=0;i<rows2.length;i++){
                                                grid.addRow(rows2[i]);     //表格增加一行数据
                                            }

                                        }

                                        // for (var s = 0; s < relationRef.length; s++) {
                                        //     for (var w = 0; w < rows2.length; w++) {
                                        //         for (var k in rows2[w]) {
                                        //             if (relationRef[s].sourceField == k) {
                                        //                 var param = relationRef[s].sourceField;
                                        //                 rows2[w] = JSON.parse(JSON.stringify(rows2[w]).replace(
                                        //                     new RegExp(param, 'g'), relationRef[s].targetField));
                                        //                 console.log(rows2[w]);
                                        //             }
                                        //         }
                                        //     }
                                        //
                                        // }
                                        // grid.addRow(rows2);
                                    }
                                }
                            }
                        }
                    },
                    error: function (data) {
                    }
                });
            }
        }
    })
}

// 打印模板跳转
function openPrintModel(printId){
    console.log(printId);
    $.ajax({
        url: ajaxUrl +'/printFormwork/findByPrintId.do',
        type: 'POST',
        data: {
            printId:printId
        },
        success: function (data) {
            // 表单数据
            // var form_data = getForm();
            // 像打印页面传递数据
            var printData = {};
            // 渲染数据
            printData.renderPageData = data;
            printData.renderPageData.formId = formId;
            // 填写内容
            printData.formContentData = edit_data;
            // 跳转到单据打印页面
            localStorage.setItem("printData",JSON.stringify(printData));
            var item = {
                iconCls: "fa fa-desktop",
                // id: formId,
                text: "打印模板:" + cFormName,
                url: "../pages/printModel/printForm.html"
            };
            parent.activeTab(item);//与父页面通信
        },
        error: function (data) {
            console.log('请求失败')
        }
    })
}
// 删除表格行
function onRemove(e, id) {
    var grid = mini.get(id);
    var row = grid.getSelected();
    if (row) {
        alert("删除：" + row.loginname)
    }
}

// 对象数组分组
function jsonByGroup(arr) {

    var map = {}, dest = [];
    for (var i = 0; i < arr.length; i++) {
        var ai = arr[i];
        if (!map[ai.c_id]) {
            dest.push({
                // cTableName: ai.cTableName,
                c_id: ai.c_id,
                cFormName: cFormName,
                cTableName: ai.cTableName,
                type: ai.type,
                data: [ai],
                gridColumns: ai.gridColumns,
                iConX: ai.iConX,
                iConY: ai.iConY,
                iLabHeight: ai.iLabHeight,
                iLabWidth: ai.iLabWidth,
                iWidth: ai.iWidth
            });
            map[ai.c_id] = ai;
        } else {
            for (var j = 0; j < dest.length; j++) {
                var dj = dest[j];
                if (dj.c_id == ai.c_id) {
                    dj.data.push(ai);
                    break;
                }
            }
        }
    }

    // console.log(dest,'分组后');
    return dest;
}

// jq id含有特殊字符的转义
function escapeJquery(srcString) {
    // 转义之后的结果
    var escapseResult = srcString;

    // javascript正则表达式中的特殊字符
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
        "]", "|", "{", "}"];

    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
        ":", ";", "<", ">", ",", "/"];

    for (var i = 0; i < jsSpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp("\\"
            + jsSpecialChars[i], "g"), "\\" + jsSpecialChars[i]);
    }

    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
            "g"), "\\" + jquerySpecialChars[i]);
    }

    return escapseResult;
}

// 字符串转换成公式
function evil(REstr) {
    console.log(REstr);
    if(REstr)

    var LEstr;
    var contactFlag = false;// 赋值等式
    if (REstr.indexOf('=') == -1) {// 不是等式
        REstr = '';
    } else {
        LEstr = REstr.substring(REstr.indexOf("[") + 1,REstr.indexOf("]"));// 提取等号左侧字段
        REstr = REstr.substring(REstr.indexOf("=") + 1);// 提取等号右侧

        // //赋值等式
        // var count = str.split('[').length -1;//单词出现的次数
        // console.log(str.indexOf('[') == 0)
        // console.log(str.indexOf(']') == str.length-1)
        // console.log(count == 1)
        // if(str.indexOf('[') == 0 && str.indexOf(']') == str.length-1 && count
        // == 1) {
        // contactFlag = true;
        // }
    }

    console.log(REstr, '公式');
    if (REstr.indexOf('undefined') == -1) {// 不含undefined字段
        console.log(REstr.indexOf('拼接'));
        if (REstr.indexOf('拼接') == -1) {
            if (REstr.indexOf('中国标准时间') > -1) {

                return REstr;
            } else {// 加减运算
                if (REstr.indexOf('+') > -1 || REstr.indexOf('-') > -1
                    || REstr.indexOf('×') > -1 || REstr.indexOf('÷') > -1) {
                    REstr = REstr.replace(new RegExp('×', 'g'), '*');
                    REstr = REstr.replace(new RegExp('÷', 'g'), '/');
                    var a = new Function('return ' + REstr)()
                    // var a = REstr;
                    console.log(a, '计算结果');
                    var b = Math.round(a * 100) / 100;
                    if (LEstr == "ShareDetailed_xgry_0003") {
                        b = ((Math.round((b * 10000)))/100).toFixed(2) + '%';
                     }
                    return b;
                }
            }
        } else {// 拼接
            REstr = REstr.replace(new RegExp('拼接', 'g'), '');
            console.log(REstr);
            return REstr;
        }

    } else {
        return '$';
    }

}

// 设置公式联动
function setLinkage(e, cMath, str, type) {
    // cMath：公式,str：可处理的公式
    var value;
    var linkType;// base类型，table类型，base+table类型
    var mathType;// 联动，计算/拼接
    console.log("cMath",cMath);
    if (cMath.indexOf('关联') > -1) {// 关联
        mathType = 'mathType_link';
        var a;
        var b;
        var c;
        var d;
        var linkId;
        var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, word) {
            if (j == 0)
                a = word;// 须填写的字段
            if (j == 1)
                b = word;// 关联的字段f

        })
        for (var i = 0; i < component_data.length; i++) {
            if (component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if (type == 'table') {// 子表之间关联
            fileldValue = e.row[c];
        } else if (type == 'base') {// 主表之间关联
            fileldValue = e.value;
        }
        var link = {
            fileld: b,
            fileldValue: fileldValue,
            returnFileld: a,
            cTableName: d
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };

    } else if (cMath.indexOf('sumCols(') > -1) {// 子表列求和
        mathType = 'mathType_sumCols';
        var sumColsField;
        var sumColsValue = '';
        $.each(cMath.match(/[^\[]+(?=\])/g), function (i, word) {// 提取[]中的字段
            if (i == 0) {
                for (var i = 0; i < component_data.length; i++) {
                    if (component_data[i].cTableField == word) {
                        sumColsField = component_data[i].c_id;
                    }
                }
            } else if (i == 1) {
                console.log('sumCols:', word);
                for (var i = 0; i < component_data.length; i++) {
                    if (component_data[i].cTableField == word) {
                        var rows = mini.get(component_data[i].c_id).getData();
                        for (var j = 0; j < rows.length; j++) {
                            for (var item in rows[j]) {
                                if (item == word) {
                                    if (rows[j][item] != ''
                                        || rows[j][item] != undefined) {
                                        sumColsValue += rows[j][item] + '+';
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        sumColsValue = sumColsValue.substring(0, sumColsValue.length - 1);
        sumColsValue = new Function('return ' + sumColsValue)();
        console.log(sumColsValue, 'sumColsValue计算结果');
        return {
            sumColsField: sumColsField,
            sumColsValue: sumColsValue,
            str: '',
            linkType: 'table',
            mathType: mathType,
            linkId: linkId
        };
    } else if (cMath.indexOf('级联') != -1) {
        mathType = 'mathType_cascade';
        var a;
        var b;
        var c;
        var d;
        var f;
        var h;
        var linkId;
        var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, word) {
            if (j == 0)
                a = word;// 须填写的字段
            if (j == 1)
                b = word;// 关联的字段
            if (j == 2)
                c = word;
            if (j == 3)
                f = word;
        })
        console.log("c:" + c);
        for (var i = 0; i < component_data.length; i++) {
            if (component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if (type == 'table') {// 子表之间关联
            fileldValue = e.row[f];
        } else if (type == 'base') {// 主表之间关联
            fileldValue = e.value;
        }
        console.log("fileldValue", fileldValue)
        var link = {
            fileld: b,
            fileldValue: fileldValue,
            returnFileld: a,
            cTableName: d,
            fileldV: c
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };

    } else if (cMath.indexOf('单据编号规则') > -1) {
        mathType = 'mathType_code';
        var a;
        var b;
        var c;
        var d;
        var f;
        var linkId;
        var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, word) {
            if (j == 0)
                a = word;// 须填写的字段
            if (j == 1)
                b = word;// 关联的字段
            if (j == 2)
                c = word;
            if (j == 3)
                f = word;
        })
        console.log("c:" + c);
        for (var i = 0; i < component_data.length; i++) {
            if (component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if (type == 'table') {// 子表之间关联
            fileldValue = e.row[f];
        } else if (type == 'base') {// 主表之间关联
            fileldValue = e.value;
        }
        console.log("fileldValue", fileldValue)
        var link = {
            fileld: b,
            fileldValue: fileldValue,
            returnFileld: a,
            cTableName: d,
            fileldV: c,
            cMath : cMath
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };

    } else if(cMath.indexOf('findTableSum(') > -1){
        mathType = 'mathType_findTableSum';
        console.log("进入跨表求和公式");
        var a;
        var b;
        var c;
        var w;
        var f;
        var linkId;
        var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, word) {
            if (j == 0)
                a = word;// 须填写的字段
            if (j == 1)
                b = word;// 关联的字段
            if (j == 2)
                c = word;
            if (j == 3)
                w = word;
        })
        console.log("B:" + b);
        for (var i = 0; i < component_data.length; i++) {
            if (component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if (type == 'table') {// 子表之间关联
            fileldValue = e.row[w];
        } else if (type == 'base') {// 主表之间关联
            fileldValue = e.value;
        }
        console.log("fileldValue", fileldValue)
        var link = {
            sumFileld: b,
            fileldValue: fileldValue,
            returnFileld: a,
            whereFileld: c,
            fileld : d,
            cMath : cMath
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };
    }else if (cMath.indexOf("if(") > -1){
        mathType = "mathType_if";
        console.log("进入if判断",cMath);

        var a;
        var b;
        var c;
        var d;
        var f;
        var g;
        var h;
        var i;
        var linkId;
        var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, word) {
            if (j == 0)
                a = word;// 须填写的字段
            if (j == 1)
                b = word;// 关联的字段
            if (j == 2)
                c = word;
            if (j == 3)
                d = word;
            if (j == 4)
                f = word;
            if (j == 5)
                g = word;
            if (j == 6)
                h = word;
            if (j == 7)
                i = word;

        });
        if (type == 'table') {// 子表之间关联
            fileldValue = e.row[i];
        } else if (type == 'base') {// 主表之间关联
            fileldValue = e.value;
        }


        var link = {
            a : a,
            b : b,
            c : c,
            d : d,
            f : f,
            g : g,
            h : h,
            i : i,
            cMath : cMath,
            findValue : fileldValue
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        }
    }

    // 计算日期区间的天数
    else if(cMath.indexOf('day(') > -1 ) {
        mathType = 'mathType_day';
        console.log("进入天数计算",cMath);

        var fieldN; // 字段名

        $.each(cMath.match(/[^\[]+(?=\])/g), function (i, word) {// 提取[]中的字段
            console.log(i, word);
            if (i == 0) {
                fieldN = word;
            }
            if (i > 0) {// 等式右侧的字段
                for (var i = 0; i < component_data.length; i++) {
                    if (component_data[i].cTableField == word) {
                        if (component_data[i].type == 'table'
                            || component_data[i].type == 'tab_table') {// 变量是表格类型
                            value = e.record[word];
                            value = mini.formatDate(value,'yyyy-MM-dd');
                            if (type == 'table' || type == 'tab_table') {
                                linkType += 'table,';
                            }
                        } else {
                            value = mini.get('right' + component_data[i].c_id)
                                .getValue();
                            linkType += 'base,'
                        }
                        var pattern = '\\[' + word + '\\]';
                        str = str.replace(new RegExp(pattern, 'g'), value);// 字段替换成值
                        var index = str.indexOf("(");
                        str = str.substring(index,str.length);
                    }
                }
            }
        });
        var link = {
            dayStr: str,
            fieldN: fieldN
        };
        return {
            str: link,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };
    }

    //  获取报销标准(a-赋值字段(标准金额),b-开始日期,c-结束日期,d-省市,f-地区)
    else if (cMath.indexOf('StandardAmount(') > -1 ) {
        mathType = 'mathType_StandardAmount';
        console.log("获取报销标准");
        var a;
        var beginTime;
        var endTime;
        var province;
        var area;
        var selectByTableName;
        $.each(cMath.match(/[^\[]+(?=\])/g), function (j, val) {
            if (j == 0) {
                a = val;// 需要赋值的字段(标准金额)
                if (val.indexOf('DetailsOfReimbursementForAccommodationExpenses') > -1 ) {
                    selectByTableName = "rstandard";
                } else if (val.indexOf('TravelSubsidy_xgry') > -1 ) {
                    selectByTableName = "TravelSubsidyStandard";
                }
            }
            if (j == 1)
                beginTime = e.record[val];// 开始日期
            if (j == 2)
                endTime = e.record[val];// 结束日期
            if (j == 3)
                province = e.record[val];// 省市
            if (j == 4)
                area = e.record[val];// 地区
        })

        var link = {
            a : a, // 需要赋值的字段(标准金额)
            beginTime : beginTime,// 开始日期
            endTime : endTime,// 结束日期
            province : province,// 省市
            area : area,// 地区
            cMath : cMath,// 公式
            selectByTableName: selectByTableName //报销标准表名
        };

        return {
            str: link,
            mathType: mathType
        }
    }

    else{// 计算/拼接
        mathType = 'mathType_other';
        $.each(cMath.match(/[^\[]+(?=\])/g), function (i, word) {// 提取[]中的字段
            console.log(i, word);
            if (i > 0) {// 等式右侧的字段
                for (var i = 0; i < component_data.length; i++) {
                    if (component_data[i].cTableField == word) {
                        if (component_data[i].type == 'table'
                            || component_data[i].type == 'tab_table') {// 变量是表格类型
                            value = e.record[word];
                            if (type == 'table' || type == 'tab_table') {
                                linkType += 'table,';
                            }
                        } else {
                            value = mini.get('right' + component_data[i].c_id)
                                .getValue();
                            linkType += 'base,'
                        }
                        var pattern = '\\[' + word + '\\]';
                        str = str.replace(new RegExp(pattern, 'g'), value);// 字段替换成值
                    }
                }
            }
        });
        return {
            str: str,
            linkType: linkType,
            mathType: mathType,
            linkId: linkId
        };
    }
}

// 表格回车时添加一行
function addRow(id) {
    var grid = mini.get(id);
    grid.on("celleditenter", function (e) {
        // console.log(grid,'回车事件');
        var index = grid.indexOf(e.record);
        if (index == grid.getData().length - 1) {
            var row = {};
            grid.addRow(row);
        }
    });
}

// 表格选择参照
function onSelectRef(e, Refer) {

    console.log(Refer, 'Refer table');
    var Ref = Refer;
    // var Ref = $.parseJSON(Refer.ref);
    mini.open({
        url: bootPATH + "../frame/frame1/pages/formDesign/selectRef.html",
        title: "选择",
        onload: function () { // 弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {
                ref: Ref.ref,
                menuId: menuId
            };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) { // 弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var RefData = iframe.contentWindow.onTableOk();
                RefData = mini.clone(RefData);
                console.log(RefData, 'selectRef');
                city_id=RefData.City_id;
                console.log(city_id);
                // 设置弹窗选择后的值
                var grid = mini.get(e.id);
                grid.cancelEdit();
                var row = grid.getSelected();
                console.log(row, 'row');
                var curCell = grid.getCurrentCell();
                var gridColumns = grid.getColumn();
                // for(var i = 0; i < gridColumns.length; i++){
                //     if(gridColumns[i].header){
                //
                //     }
                // }
                var field = curCell[1].field;
                console.log(field, 'field');// 当前单元格
                var updateData = {};
                console.log(Ref.ref.cTableField);
                console.log(RefData[Ref.ref.cTableField]);
                updateData[field] = RefData[Ref.ref.cTableField];
                // updateData[field] = RefData["orderPeople"];
                grid.updateRow(row, updateData);
            }
        }
    })
}

// 表单操作
function getForm() {
    var form = new mini.Form("#formField");
    var data = form.getData();
    console.log(data);
    return data;
}

function setForm(obj) {
    var form = new mini.Form("#formField");
    form.setData(obj, false);
}

function resetForm() {
    var form = new mini.Form("#formField");
    form.reset();
}

function clearForm() {
    var form = new mini.Form("#formField");
    form.clear();
}

function clearTable() {
    console.log(component_data);
    for (var i = 0; i < component_data.length; i++) {
        if (component_data[i].type.indexOf('table') > -1) {
            mini.get(component_data[i].c_id).setData([]);
        }
    }
}

// 表格--右键菜单
function onBeforeOpenGrid(e, id) {
    var grid = mini.get(id);
    var menu = e.sender;

    var row = grid.getSelected();
    // var rowIndex = grid.indexOf(row);
    if (!row) {
        e.cancel = true;
        e.htmlEvent.preventDefault();// 阻止浏览器默认右键菜单
        return;
    }
}

function actions(act) {
    if (act == 'add') {
        action = 'add';
        save_data = [];

        formCode = new Date().getTime();
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").enable();
        mini.get("abandon").enable();
        mini.get("refer").enable();
        mini.get("submission").enable();
        mini.get("copy").disable();
        unmask();
        clearForm();//清空主表数据
        var form = new mini.Form("formField"); // 得到页面上的表单
        form.setData(singleObj);
        clearTable();//清空子表数据
        var codingData = localStorage.getItem('coding');
        codingData = JSON.parse(codingData);
        form.setData(codingData);

        var singleObj = {
            single_person_id: userInfoObj.userId,
            single_person: userInfoObj.uName
        }
        // 设置主表当前日期
        for (var i = 0; i < datepick_main.length; i++) {
            if (datepick_main[i].cDateDefault == 'true') {
                mini.get('right' + datepick_main[i].c_id).setValue(new Date());
            }
        }

        // 设置表格默认日期
        // datepick_child的数据是否默认都为true
        for (var i = 0; i < datepick_child.length; i++) {
            var grid = mini.get(datepick_child[i].c_id);
            var rows = grid.getData()// 获取所有行
            for (var j = 0; j < rows.length; j++) {
                var up = {};
                up[datepick_child[i].cTableField] = new Date();
                grid.updateRow(rows[j], up);
            }
        }
        //默认父级id赋值
        for (var p = 0; p < pid_data.length; p++) {
            if (pid_data[i]) {
                mini.get('right' + pid_data[i].c_id).setText('-1');
                mini.get('right' + pid_data[i].c_id).setValue('-1');
            }
        }
        $.ajax({
            url: ajaxUrl + "/Coding/addCoding.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
            type: "post",
            dataType: "json",
            data: {
                formId: formId
            },
            success: function (data) {
                console.log(data, '数据');
                form.setData(data);

                coding=data.codingId;
                localStorage.setItem("coding",JSON.stringify(data));

            },
            error: function (data) {
            }
        });

    } else if (act == 'edit') {
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").enable();
        mini.get("copy").enable();

        innerMode = 'inner_edit';
        arr_save = $.parseJSON(arr_save);
        // 获取编辑的数据，赋值
        inner_obj = {
            cTableName: arr_save[0].cTableName,// 主表的名称
            formId: formId,// 表单id
            mTableId: arr_save[0].obj.id
            // 列的id
        }
        $.ajax({
            url: ajaxUrl + "/formltems/formByMtableId.do",
            type: "POST",
            data: {
                obj: JSON.stringify(inner_obj)
            },
            success: function (data) {
                console.log(data, 'inner编辑的数据');
                setEditData(data[0]);
            },
            error: function (data) {
            }
        });

        unmask();
    } else if (act == 'save') {
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").enable();
        mini.get("copy").enable();
        save();
    } else if (act == 'remove') {
        if (save_data.length != 0) {
            removeForm();

            function removeForm() {
                var del_data = [];
                for (var i = 0; i < save_data.length; i++) {
                    del_data.push({
                        cTableName: save_data[i].cTableName,
                        mTableId: save_data[0].id,
                        formId: formId
                    })
                }
                del_data = reduce(del_data, 'cTableName');// arr:去重的数组，type：去重的参照索引
                console.log(del_data, '删除的数据');

                $.ajax({
                    url: ajaxUrl + "/formltems/deleteFormSource.do",
                    type: "post",
                    dataType: "json",
                    traditional: true,
                    data: {
                        obj: JSON.stringify(del_data)
                    },
                    success: function (data) {
                        console.log(data, '数据');
                        mini.showTips({
                            content: "删除成功",
                            state: 'success',
                            x: 'Center',
                            y: 'Top',
                            timeout: 2000
                        });
                        clearForm();
                        clearTable()
                        mask();

                        mini.get("add").enable();
                        mini.get("edit").disable();
                        mini.get("save").disable();
                        mini.get("remove").disable();
                        mini.get("cancel").disable();
                        mini.get("approve").disable();
                        mini.get("abandon").disable();
                        mini.get("refer").enable();
                    },
                    error: function (data) {
                        mini.alert('删除失败')
                    }
                });
            }
        } else {
            // mini.alert('表单尚未保存!');
        }
    } else if (act == 'cancel') {

        mini.get("add").enable();
        mini.get("edit").disable();
        mini.get("save").disable();
        mini.get("remove").disable();
        mini.get("cancel").disable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").disable();
        mask();
        cancel();

    } else if (act == 'reference') {// 参照

    } else if (act == 'submission') {
        onSubmission();
    }else if(act=="enclosure"){

        mini.open({

            url:"Attachmentdetails.html",
            title: "附件详情", width: 800, height: 600,

            onload: function () {
                    var iframe = this.getIFrameEl();
                    var data = {
                        fujian:fujian
                    };
                    iframe.contentWindow.SetData(data);

            },
            ondestroy: function (action) {
                var iframe=this.getIFrameEl();
                var data=iframe.contentWindow.GetData();
                ids=mini.clone(data);
                console.log(ids);

            }
        })
    }else if (act == 'copy') {
        alert("1569");
        action = 'copy';


        formCode = new Date().getTime();
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").enable();
        mini.get("abandon").enable();
        mini.get("refer").enable();
        mini.get("submission").enable();
        mini.get("copy").disable();
        unmask();

        var form = new mini.Form("formField"); // 得到页面上的表单
        var data=form.getData();
        console.log(data);
        var data1={ formId: formId, cTableName:mTableName,id:idd1};

        console.log(mTableName);

       //   mTableName1=mini.clone(data1);
       //   console.log(typeof mTableName1);
       // mTableName2=mTableName1.cTableName;
       //
       //   console.log(typeof mTableName2);


//         form.setData(singleObj);
//
//         var singleObj = {
//             single_person_id: userInfoObj.userId,
//             single_person: userInfoObj.uName
//         }
//         // 设置主表当前日期
//         for (var i = 0; i < datepick_main.length; i++) {
//             if (datepick_main[i].cDateDefault == 'true') {
//                 mini.get('right' + datepick_main[i].c_id).setValue(new Date());
//             }
//         }
//
//         // 设置表格默认日期
//         // datepick_child的数据是否默认都为true
//         for (var i = 0; i < datepick_child.length; i++) {
//             var grid = mini.get(datepick_child[i].c_id);
//             var rows = grid.getData()// 获取所有行
//             for (var j = 0; j < rows.length; j++) {
//                 var up = {};
//                 up[datepick_child[i].cTableField] = new Date();
//                 grid.updateRow(rows[j], up);
//             }
//         }
//         //默认父级id赋值
//         for (var p = 0; p < pid_data.length; p++) {
//             if (pid_data[i]) {
//                 mini.get('right' + pid_data[i].c_id).setText('-1');
//                 mini.get('right' + pid_data[i].c_id).setValue('-1');
//             }
//         }
        $.ajax({
            url: ajaxUrl + "/sqlAction/copyById.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
            type: "post",
            dataType: "json",
            data: {
                obj: JSON.stringify(data1)
            },
            success: function (data) {
                console.log(data[0]);
                var mainFormData=data[0];
                var data1  = {};
                for(var key in mainFormData){
                    if(mainFormData[key].indexOf('null') == -1){
                        data1[key] = mainFormData[key].split('_')[1];
                    }else{
                        data1[key] = '';

                    }
                }
                console.log(mainFormData[mTableName], '数据');

                var data11=mainFormData[mTableName];
                console.log(typeof data11);


                form.setData(data1);

                coding=data.codingId;
                localStorage.setItem("coding",JSON.stringify(data));

            },
            error: function (data) {
            }
        });

    }else if(act=="onPrint"){
        console.log('打印');
        // //获取当前页面html
        // var printBody = document.body.innerHTML;
        // // 得到需要打印的部分
        // document.body.innerHTML = document.querySelector('.page').innerHTML;
        // // 打印
        // window.print();
        // // 页面还原
        // document.body.innerHTML = printBody;
    }
}

// 设置遮罩
function mask() {
    mini.mask({
            el: document.getElementById('formField'),
            html: "<div></div>",
            // cls : "mini-mask-loading",
            style: "height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
        });
}

// 取消遮罩
function unmask() {
    mini.unmask(document.getElementById('formField'));
}

// 表格增行
function onAddRow(e, id) {
    var newRow = {
        name: "New Row"
    };
    var grid = mini.get(id);
    grid.addRow(newRow);
    // grid.beginEditCell(newRow, "LoginName");
}

// 表格删行
function onRemoveRow(e, id) {
    var grid = mini.get(id);
    var cTableName;
    for (var k = 0; k < arr_table.length; k++) {
        if (arr_table[k].c_id == id.id) {
            cTableName = arr_table[k].cTableName;
        }
    }
    var rows = grid.getSelecteds();
    var data = grid.getData();
    if (rows.length > 0) {
        grid.removeRows(rows, true);
        console.log(rows, 'del rows');
        var del_data = [];
        for (var i = 0; i < rows.length; i++) {
            if (rows[i]._state != 'added') {
                del_data.push({
                    id: rows[i].id,
                    cTableName: cTableName
                });
            }
        }
        console.log(del_data, 'del_data');

        // $.ajax({
        // 	type : 'post',
        // 	url : ajaxUrl + '/dbsource/dbDelete.do',
        // 	data : JSON.stringify(del_data),
        // 	dataType : 'json',
        // 	contentType : 'application/json',
        // 	success : function(data) {
        // 		console.log(data);
        // 	},
        // 	error : function(message) {
        // 		// console.log(message);
        // 	}
        // })
    }
}
//表格计算行(计算天数)
function onCompute(e, id){
    //获取表格
    var grid = mini.get(id);
    //获取行
    var row = grid.getSelected();
    //判断是否获取
    if(row){
        var str;
        //如果开始日期和结束日期都有值
        if(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0002'] && row['DetailsOfReimbursementForAccommodationExpenses_xgry_0003']){
            //计算天数
            //var endTime = row['DetailsOfReimbursementForAccommodationExpenses_xgry_0003'];
            //var startTime = row['DetailsOfReimbursementForAccommodationExpenses_xgry_0002'];
            //str = "(" + mini.formatDate(endTime,'yyyy-MM-dd') + '-' + mini.formatDate(startTime,'yyyy-MM-dd') + ")";
            // if(endTime && startTime)
            // //判断是否是时间戳(没有-的是时间戳)，如果是就转换格式，如果不是就直接拼接
            // if((endTime.indexOf('-') == -1) && (endTime.indexOf('-') == -1)){
            //     str = "(" + mini.formatDate(endTime,'yyyy-MM-dd') + '-' + mini.formatDate(startTime,'yyyy-MM-dd') + ")";
            // }else{
            //     str = "(" + endTime + '-' + startTime + ")";
            // }
            //如果省市和城区都有值,计算标准金额
            if(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0004'] && row['DetailsOfReimbursementForAccommodationExpenses_xgry_0005']){
                //计算标准金额参数
                str = {
                    a: "DetailsOfReimbursementForAccommodationExpenses_xgry_0014",
                    beginTime: mini.formatDate(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0002'],'yyyy-MM-dd'),
                    endTime: mini.formatDate(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0003'],'yyyy-MM-dd'),
                    province: row['DetailsOfReimbursementForAccommodationExpenses_xgry_0004'],
                    area: row['DetailsOfReimbursementForAccommodationExpenses_xgry_0005'],
                    selectByTableName: 'rstandard'
                };
                //计算
                $.ajax({
                    type: 'POST',
                    url:ajaxUrl + '/sqlAction/findStandardAmount.do',
                    dataType: 'json',
                    contentType: "application/json",
                    data: JSON.stringify(str),
                    success: function (data) {
                        console.log("报销标准",data.data)
                        //e.cellHtml = data.data;
                        //e.row[e.field] = data.data;
                        row['DetailsOfReimbursementForAccommodationExpenses_xgry_0014'] = data.data;
                        //更新行数据
                        grid.updateRow(row, row);
                        //报销金额=标准金额*天数
                        var momey = parseInt(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0014']);            //标准金额
                        var daysNum = parseInt(row['DetailsOfReimbursementForAccommodationExpenses_xgry_0006']);          //天数
                        if((momey != NaN) && (daysNum != NaN)){
                            var product = (momey * daysNum);
                            //计算报销金额(并赋值)
                            row['DetailsOfReimbursementForAccommodationExpenses_xgry_0007'] = momey * daysNum;
                            //更新行数据
                            grid.updateRow(row, row);
                        }else{
                            mini.alert('日期和标准金额需要是数字格式');
                        }
                    }
                })

            }else{
                mini.alert('请选择省市和城区');
            }

        }else if(row['TravelSubsidy_xgry_0001'] && row['TravelSubsidy_xgry_0002']){
            // str = "(" + mini.formatDate(row['TravelSubsidy_xgry_0002'],'yyyy-MM-dd') + '-' + mini.formatDate(row['TravelSubsidy_xgry_0001'],'yyyy-MM-dd') + ")";
            // $.ajax({
            //     type: 'POST',
            //     url: ajaxUrl + '/sqlAction/day.do',
            //     dataType: 'json',
            //     contentType: "application/json",
            //     data: JSON.stringify(str),
            //     //data: str,
            //     success: function (data) {
            //         console.log(data);
            //         row['TravelSubsidy_xgry_0006'] = data;
            //         grid.updateRow(row, row);
            //
            //     }
            // })
            //计算差旅补贴
            if(row['TravelSubsidy_xgry_0003'] && row['TravelSubsidy_xgry_0004']){
                //计算标准金额参数
                str = {
                    a: "TravelSubsidy_xgry_0006",
                    beginTime: mini.formatDate(row['TravelSubsidy_xgry_0001'],'yyyy-MM-dd'),
                    endTime: mini.formatDate(row['TravelSubsidy_xgry_0002'],'yyyy-MM-dd'),
                    province: row['TravelSubsidy_xgry_0003'],
                    area: row['TravelSubsidy_xgry_0004'],
                    selectByTableName: 'TravelSubsidyStandard'
                };
                //计算报销标准
                $.ajax({
                    type: 'POST',
                    url:ajaxUrl + '/sqlAction/findStandardAmount.do',
                    dataType: 'json',
                    contentType: "application/json",
                    data: JSON.stringify(str),
                    success: function (data) {
                        console.log("报销标准",data.data)
                        //e.cellHtml = data.data;
                        //e.row[e.field] = data.data;
                        row['TravelSubsidy_xgry_0006'] = data.data;
                        //更新行数据
                        grid.updateRow(row, row);
                        //计算补贴总金额:补贴标准*天数
                        var daysNum2 = parseInt(row['TravelSubsidy_xgry_0005']);          //天数
                        var moneys2 = parseInt(row['TravelSubsidy_xgry_0006']);            //标准
                        if((moneys2 != NaN) && (daysNum2 != NaN)){
                            //补贴总金额赋值
                            row['TravelSubsidy_xgry_0009'] = daysNum2 * moneys2;
                            //更新行数据
                            grid.updateRow(row, row);
                        }else{
                            mini.alert('日期和标准金额需要是数字格式');
                        }
                    }
                })
            }else{
                mini.alert('请选择省市和城区');
            }
        }else{
            mini.alert('请输入开始日期和结束日期');
        }
    }else{
        mini.alert('请获取行数据');
    }
}

// 保存
var grid_datas = [];
var arr_save = [];

function save() {

    if (arr_tab_table.length > 0) {
        arr_table = jsonByGroup(arr_tab_table);// 表格按数据库表名分组
    } else {
        arr_tab_table = mini.clone(arr_table);
        arr_table = jsonByGroup(arr_table);// 表格按数据库表名分组
    }

    // arr_table = jsonByGroup(arr_tab_table);// 表格按数据库表名分组

    // 表单验证
    var form = new mini.Form("#formField");
    form.validate();
    if (form.isValid() == false){
        return;
    }

    // 单元格验证
    for (var p = 0; p < arr_table.length; p++) {
        var grid = mini.get(arr_table[p].c_id);
        grid.validate();
        if (grid.isValid() == false) {
            // alert("请校验输入单元格内容");
            var error = grid.getCellErrors()[0];
            grid.beginEditCell(error.record, error.column);
            return;
        }
    }

    // 提交数据
    arr_child = [];
    grid_datas = [];
    var grid_datas_id = [];
    console.log(arr_main, 'arr_main保存前');
    console.log(arr_table, 'arr_table');
    console.log(arr_tab_table, 'arr_tab_table');
    var child = [];// 合并子表数据
    child = arr_table.concat(arr_tab_table);
    var form_data = getForm();

    var pidFlag = false;
    for (item in form_data) {
        console.log(form_data[item]);
        // console.log(new Date(form_data[item]));
        // console.log(new Date(form_data[item]).toString());
        // if(new Date(form_data[item]).toString().indexOf('中国标准时间')>-1) {
        // form_data[item] = standardToDate(form_data[item],'-');
        // console.log(form_data[item]);
        // }

        for (i in arr_main.obj) {
            if (i == item) {
                arr_main.obj[i] = form_data[item];
            }
            if (i == 'parent_level') {
                pidFlag = true;
                if (arr_main.obj[i] == '') {
                    arr_main.obj[i] = -1;
                }
            }
        }
    }
    if (!pidFlag) {//没有pid
        arr_main.obj.parent_level = -1;
    }

    var time = new Date().getTime();
    // var time = guid();
    arr_main.obj.id = time;
    arr_main.tableType = 'main';
    console.log(arr_main, 'arr_main保存后');

    for (var i = 0; i < child.length; i++) {
        // 每个arr[i]是一个表格
        var id = child[i].c_id;
        var cols = child[i].gridColumns;
        var data = child[i].data;
        var grid_data = mini.get(id).getData();

        if (grid_datas_id.indexOf(id) == -1) {
            grid_datas_id.push(id);
            grid_datas.push({
                id: id,
                data: grid_data
            });

            for (var j = 0; j < grid_data.length; j++) {
                // delete grid_data[j]._id;
                // delete grid_data[j]._uid;
                delete grid_data[j]._state;
                for (var item in grid_data[j]) {
                    if (item.indexOf('$') > -1) {

                        var a = item.match(/\$(\S*)/)[1];
                        grid_data[j][a] = grid_data[j][item];
                        delete grid_data[j][item];
                    }
                }

                arr_child.push({
                    cTableName: child[i].cTableName,
                    tableType: 'child',
                    obj: grid_data[j]
                });
                arr_child[arr_child.length - 1].obj[child[i].cTableName + '_single_person_id'] = userInfoObj.userId // 制单人id
                arr_child[arr_child.length - 1].obj[child[i].cTableName + '_single_person'] = userInfoObj.uName // 制单人

                arr_child[arr_child.length - 1].obj.id = new Date().getTime() + j * 100;
                // arr_child[j].obj.id = guid();
                arr_child[arr_child.length - 1].obj.mTableId = time;

                if (arr_child[arr_child.length - 1].obj.name = 'New Row') {
                    delete arr_child[arr_child.length - 1].obj.name;
                }
            }
        }
    }

    console.log(grid_datas, 'grid_datas');
    console.log(arr_child, 'arr_child保存后');
    // console.log(grid_datas,'grid_datas');

    // 合并
    arr_save = [];
    arr_save[0] = arr_main;
    arr_save[0].grid_data = JSON.stringify(grid_datas);
    arr_save[0].cFormName = cFormName;

    // 添加默认制单人
    arr_save[0].obj[mTableName + '_single_person_id'] = userInfoObj.userId // 制单人id
    arr_save[0].obj[mTableName + '_single_person'] = userInfoObj.uName // 制单人
    //处理单据状态显示
    switch (arr_save[0].obj[formSh.cTableName + '_state']) {
        case '未提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '0';
            break;
        case '已提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '1';
            break;
        case '审批中':
            arr_save[0].obj[formSh.cTableName + '_state'] = '2';
            break;
        case '终审':
            arr_save[0].obj[formSh.cTableName + '_state'] = '3';
            break;
        case '驳回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '4';
            break;
        case '中止':
            arr_save[0].obj[formSh.cTableName + '_state'] = '5';
            break;
        case '撤回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '6';
            break;
        default:
            arr_save[0].obj[formSh.cTableName + '_state'] = '';
    }
    for (var i = 0; i < arr_child.length; i++) {

        arr_save.push(arr_child[i]);
    }
    console.log(arr_save, '保存的数据');

    var url;
    // innerMode == 'inner_edit';
    if (action == 'edit') {
        console.log(edit_form, 'edit_form');
        console.log(edit_table, 'edit_table');
        console.log(mTableName + '_id', 'ID');
        console.log(edit_form[mTableName + '_id'], 'ID');
        //save_backData = {id: edit_form[mTableName + '_id']};
        save_backData = {id: edit_form[mTableName + '_id'].split('_')[0]};
        url = ajaxUrl + "/sqlAction/update.do";
        for (var i = 0; i < arr_save.length; i++) {
            if (i == 0) {
                // arr_save[i].obj.id = edit_form.id;
                arr_save[i].obj.id = save_backData.id;
                arr_save[i].formId = formId;
                // arr_save[i].formCode = formCode;
            } else {
                arr_save[i].obj.mTableId = edit_form.id;
                arr_save[i].mTableId = edit_form.id;
                arr_save[i].formId = formId;
            }
        }

    } else {
        if (innerMode == 'inner_edit') {
            url = ajaxUrl + "/sqlAction/update.do";
            for (var i = 0; i < arr_save.length; i++) {
                if (i == 0) {
                    // arr_save[i].obj.id = edit_form.id;
                    arr_save[i].obj.id = save_backData.id;
                    arr_save[i].formId = formId;
                    // arr_save[i].formCode = formCode;
                } else {
                    arr_save[i].obj.mTableId = edit_form.id;
                    arr_save[i].mTableId = edit_form.id;
                    arr_save[i].formId = formId;
                }
            }
        } else {
            url = ajaxUrl + "/sqlAction/insert.do";
        }
    }

    for (var i = 0; i < arr_save.length; i++) {
        for (var item in complex_add_values) {
            if (i == 0) {
                arr_save[i].obj[item] = complex_add_values[item];
            }
        }
    }

    console.log(arr_save, '转为字符串之前');
    //arr_save.obj.derpayment_single_person = userInfoObj.userName;
    arr_save[0].obj[mTableName + '_single_person'] = userInfoObj.userName // 制单人
    //处理单据状态显示
    switch (arr_save[0].obj[formSh.cTableName + '_state']) {
        case '已提交':
            arr_save[0].obj[formSh.cTableName + '_state'] = '1';
            break;
        case '审批中':
            arr_save[0].obj[formSh.cTableName + '_state'] = '2';
            break;
        case '终审':
            arr_save[0].obj[formSh.cTableName + '_state'] = '3';
            break;
        case '驳回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '4';
            break;
        case '中止':
            arr_save[0].obj[formSh.cTableName + '_state'] = '5';
            break;
        case '撤回':
            arr_save[0].obj[formSh.cTableName + '_state'] = '6';
            break;
    }
    save_data = arr_save;// 全局

    if(ids == 'undefined'){

    }else {
        console.log(arr_save[0]);
        console.log(typeof arr_save[0]);
        arr_save[0].obj['ids'] = ids;
    }

    arr_save = JSON.stringify(arr_save);
    //console.log(complex_add_values);
    console.log(arr_save, '保存数据');
    // cTableName
    // url = "http://192.168.31.65:8080/bpm/dbsource/dbInsert.do";
    $.ajax({
        type: 'post',
        url: url,
        dataType: 'json',
        data: arr_save,
        contentType: 'application/json',
        success: function (data) {

            var obj={id:data.id};
            idd=mini.clone(obj);
             idd1=idd.id
            console.log(idd1);
            localStorage.setItem("obj",JSON.stringify(obj));
            console.log(data);
            save_backData = data;
            if (data.state == "success") {
                mini.showTips({
                    content: data.message,
                    state: 'success',
                    x: 'Center',
                    y: 'Top',
                    timeout: 3000
                });
            } else {
                mini.showTips({
                    content: data.message,
                    state: 'error',
                    x: 'Center',
                    y: 'Top',
                    timeout: 3000
                });
            }

            mini.get("add").enable();
            mini.get("edit").enable();
            mini.get("save").disable();
            mini.get("remove").enable();
            mini.get("cancel").disable();
            mini.get("approve").enable();
            mini.get("abandon").enable();
            mini.get("refer").disable();
            mask();
            // console.log(t_arr,'表格id');
            // parent.removeTab();//保存成功，关闭页面
        },
        error: function () {
            mini.alert('保存失败');
        }
    })
}

//附件上传
function onFileSelect(e) {
    var fileupload = mini.get("fileupload1");
    fileupload.startUpload();
}

function onUploadSuccess(e) {
    alert("上传成功：" + e.serverData);
    this.setText("");
}

function onUploadError(e) {

}


function reduce(arr, type) {
    var hash = {};
    arr = arr.reduce(function (item, next) {
        hash[next[type]] ? '' : hash[next[type]] = true && item.push(next);
        return item
    }, [])
    // console.log(arr,'属性数组');
    return arr;
}

// 时间戳转为日期格式
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date
            .getMonth() + 1)
        + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y + M + D ;
}

// 中国标准时间转为日期格式
function standardToDate(date, type) {// 中国标准时间转为时间格式
    var d = new Date(date);
    // d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' +
    // d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
    return d.getFullYear() + type + (d.getMonth() + 1) + type + d.getDate();
}

function setEditData(edit_data) {
    console.log(edit_data);
    var formField = $("#formField").children();
    console.log(formField, 'formField');
    for (var i = 0; i < formField.length; i++) {
        console.log(formField[i].id, 'id');
        if (formField[i].className == 'form_items') {// 主表组件

            var form = new mini.Form("#" + formField[i].id);
            form.setData(edit_data[inner_obj.cTableName][0], false);
            var index = formField[i].id.indexOf('buttonedit')

            if (index > -1) {
                console.log(edit_data[inner_obj.cTableName][0]);
                for (var item in edit_data[inner_obj.cTableName][0]) {
                    var setBE = edit_data[inner_obj.cTableName][0];
                    if (item == formField[i].children[1].children[1].name) {
                        mini.get("right" + formField[i].id)
                            .setText(setBE[item]);
                    }
                }
            }
            edit_form = edit_data[inner_obj.cTableName][0];

        } else {// 表格
            if (formField[i].className.indexOf('mini-menu') == -1) {

                var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
                grid.setData("");
                var temp = formField[i].childNodes[2].className.split(' ');
                var mtableName;
                for (var m = 0; m < temp.length; m++) {
                    if (temp[m].indexOf('mtable-') > -1) {
                        mtableName = temp[m]
                            .substring(temp[m].indexOf("-") + 1);
                    }
                }

                // var e = edit_data[formField[i].id.substring(8)];
                // for(var k = 0; k <e.length; k++) {
                // e[k].cTableName = formField[i].id.substring(8);//加入子表名
                // }
                if (edit_data[mtableName] == []) {
                    grid.setData([{}, {}]);
                } else {
                    grid.setData(edit_data[mtableName], false);
                }
            }
        }
    }
}

// 提交并保存
function onSubmission() {
    arr_table = jsonByGroup(arr_table);// 表格按数据库表名分组
    // 表单验证
    var form = new mini.Form("#formField");
    form.validate();
    if (form.isValid() == false)
        return;
    // 单元格验证
    for (var p = 0; p < arr_table.length; p++) {
        var grid = mini.get(arr_table[p].c_id);
        grid.validate();
        if (grid.isValid() == false) {
            // alert("请校验输入单元格内容");
            var error = grid.getCellErrors()[0];
            grid.beginEditCell(error.record, error.column);
            return;
        }
    }
    // 提交数据
    arr_child = [];
    grid_datas = [];
    var grid_datas_id = [];
    var child = [];// 合并子表数据
    child = arr_table.concat(arr_tab_table);
    var form_data = getForm();

    for (item in form_data) {
        console.log(form_data[item]);
        for (i in arr_main.obj) {
            if (i == item) {
                arr_main.obj[i] = form_data[item];
            }
        }
    }
    var time = new Date().getTime();
    // var time = guid();
    //arr_main.obj.id = time;
    console.log(arr_main.obj.id);
    var sendId = arr_main.obj.id; // 提交用的id
    for (var i = 0; i < child.length; i++) {
        // 每个arr[i]是一个表格
        var id = child[i].c_id;
        var cols = child[i].gridColumns;
        var data = child[i].data;
        var grid_data = mini.get(id).getData();

        if (grid_datas_id.indexOf(id) == -1) {
            grid_datas_id.push(id);
            grid_datas.push({
                id: id,
                data: grid_data
            });

            for (var j = 0; j < grid_data.length; j++) {
                delete grid_data[j]._state;
                if (grid_data[j].name = 'New Row') {
                    delete grid_data[j].name;
                }
                arr_child.push({
                    cTableName: child[i].cTableName,
                    obj: grid_data[j]
                });
                arr_child[j].obj.id = new Date().getTime() + j * 100;
                // arr_child[j].obj.id = guid();
                arr_child[j].obj.mTableId = time;
            }
        }
    }

    // 合并
    arr_save = [];
    arr_save[0] = arr_main;
    arr_save[0].grid_data = JSON.stringify(grid_datas);
    arr_save[0].cFormName = cFormName;

    for (var i = 0; i < arr_child.length; i++) {
        arr_save.push(arr_child[i]);
    }

    var url;
    // innerMode == 'inner_edit';
    if (action == 'edit') {
        url = ajaxUrl + "/sqlAction/update.do";
        for (var i = 0; i < arr_save.length; i++) {
            if (i == 0) {
                arr_save[i].obj.id = edit_form.id;
                arr_save[i].formId = formId;
                // arr_save[i].formCode = formCode;
            } else {
                arr_save[i].obj.mTableId = edit_form.id;
                arr_save[i].mTableId = edit_form.id;
                arr_save[i].formId = formId;
            }
        }

    } else {
        if (innerMode == 'inner_edit') {
            url = ajaxUrl + "/sqlAction/update.do";
            for (var i = 0; i < arr_save.length; i++) {
                if (i == 0) {
                    arr_save[i].obj.id = edit_form.id;
                    arr_save[i].formId = formId;
                    // arr_save[i].formCode = formCode;
                } else {
                    arr_save[i].obj.mTableId = edit_form.id;
                    arr_save[i].mTableId = edit_form.id;
                    arr_save[i].formId = formId;
                }
            }
        } else {
            url = ajaxUrl + "/sqlAction/insert.do";
        }
    }

    for (var i = 0; i < arr_save.length; i++) {
        for (var item in complex_add_values) {
            if (i == 0) {
                arr_save[i].obj[item] = complex_add_values[item];
            }
            // if(arr_save.length == 1) {
            // 	arr_save[i][item] = complex_add_values[item];
            // }else {
            // 	if(i==0) {
            // 		arr_save[i][item] = complex_add_values[item];
            // 	}else {
            // 		arr_save[i][item] = arr_save[0].obj.id;
            // 	}
            // }
        }
    }
    console.log(arr_save, '保存的数据');
    // 添加默认制单人
    arr_save[0].obj.single_person_id = userInfoObj.userId // 制单人id
    arr_save[0].obj.single_person = userInfoObj.uName // 制单人
    arr_save[0].obj.state = '0' // 状态


    save_data = arr_save;// 全局
    arr_save = JSON.stringify(arr_save);
    console.log(save_data);
    var cTableName=save_data[0].cTableName;
    var userName=save_data[0].obj[cTableName+"_single_person"];
    // 提交
      var obj=localStorage.getItem("obj");
        console.log(obj);
        var obj=$.parseJSON(obj);
        var sendId = obj.id;
        $.ajax({
            url: ajaxUrl + "/activitiTaskController/startApply.do",
            data: {
                taskId: sendId,
                formId: formId,
                userName:userName
            },
            type: 'post',
            success: function (data) {
                alert("提交成功");
                console.log(data, '新增提交返回');
                var taskId = data.taskId;
                var msg = '消息有新任务|' + userInfoObj.userId+'|'+data.userInfo.userId;
                ;
                console.log(msg, '要发送的消息');
                send(msg);
            },
            error: function (data) {
                alert("提交失败");
                console.log(data);
            }
        });
}

//随机数
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}
//判断申请金额不能为0，当为0时会无法保存提交报红警
function onGtzero(e){
    if(e.isValid){
        if(e.value<=0){
            e.errorText="金额不能为零";
            e.isValid=false;
        }

    }
}
//取消
function cancel() {
    var codingData = localStorage.getItem('coding');
    codingData = JSON.parse(codingData);
    var coding=codingData.codingId;
    console.log(coding);
    $.ajax({
        url: ajaxUrl + "/Coding/deleteCodingById.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
        type: "post",
        dataType: "json",
        data: {
            codingId:coding


        },
        success: function (data) {
            console.log(data, '数据');
            clearForm();//清空主表数据

        },
        error: function (data) {
            // alert("444")
        }
    });

}
//截取字符串_方法
//var data="aaa-bbb";
//intercept(data,0);输出为aaa
//intercept(data,1)输出
function intercept(obj,state) {
    var index=obj.lastIndexOf("\_");
    if(state==0){
        obj=obj.substring(0,index);
    }else{
        obj=obj.substring(index+1,obj.length);
    }
    return obj;
}
function intercept2(obj,state) {
    var index=obj.lastIndexOf("\"");
    if(state==0){
        obj=obj.substring(0,index);
    }else{
        obj=obj.substring(index+1,obj.length);
    }
    return obj;
}